[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
return $regs['domain'];
} else {
$isIp = (bool) ip2long($pieces['host']);
if ($isIp) {
return $pieces['host'];
}
}
return false;
}
function siteMap() {
_error_log("siteMap: start");
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 0);
global $global, $advancedCustom;
$date = date('Y-m-d\TH:i:s') . "+00:00";
$xml = '
' . $global['webSiteRootURL'] . '
' . $date . '
always
1.00
' . $global['webSiteRootURL'] . 'help
' . $date . '
monthly
0.50
' . $global['webSiteRootURL'] . 'about
' . $date . '
monthly
0.50
' . $global['webSiteRootURL'] . 'contact
' . $date . '
monthly
0.50
' . $global['webSiteRootURL'] . 'channels
' . $date . '
daily
0.80
';
$_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit;
_error_log("siteMap: rowCount {$_REQUEST['rowCount']} ");
$_POST['sort']['modified'] = "DESC";
$users = User::getAllUsersThatHasVideos(true);
_error_log("siteMap: getAllUsers " . count($users));
foreach ($users as $value) {
$xml .= '
' . User::getChannelLink($value['id']) . '
' . $date . '
daily
0.90
';
}
$xml .= '
';
$_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit;
$_POST['sort']['modified'] = "DESC";
$rows = Category::getAllCategories();
_error_log("siteMap: getAllCategories " . count($rows));
foreach ($rows as $value) {
$xml .= '
' . $global['webSiteRootURL'] . 'cat/' . $value['clean_name'] . '
' . $date . '
weekly
0.80
';
}
$xml .= '';
$_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit * 10;
$_POST['sort']['created'] = "DESC";
$rows = Video::getAllVideos(!empty($advancedCustom->showPrivateVideosOnSitemap) ? "viewableNotUnlisted" : "publicOnly");
_error_log("siteMap: getAllVideos " . count($rows));
foreach ($rows as $video) {
$videos_id = $video['id'];
//_error_log("siteMap: getAllVideos videos_id {$videos_id} start");
$source = Video::getSourceFile($video['filename']);
if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) {
$img = $source['url'];
$data = getimgsize($source['path']);
$imgw = $data[0];
$imgh = $data[1];
} elseif ($video['type'] == "audio") {
$img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg";
}
$type = 'video';
if ($video['type'] === 'pdf') {
$type = 'pdf';
}
if ($video['type'] === 'article') {
$type = 'article';
}
$images = Video::getImageFromFilename($video['filename'], $type);
if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') {
$img = $images->posterPortrait;
$data = getimgsize($images->posterPortraitPath);
$imgw = $data[0];
$imgh = $data[1];
} else {
$img = $images->poster;
}
$description = str_replace(array('"', "\n", "\r"), array('', ' ', ' '), empty(trim($video['description'])) ? $video['title'] : $video['description']);
$duration = parseDurationToSeconds($video['duration']);
if ($duration > 28800) {
// this is because this issue https://github.com/WWBN/AVideo/issues/3338 remove in the future if is not necessary anymore
$duration = 28800;
}
$xml .= '
' . Video::getLink($video['id'], $video['clean_title']) . '
' . $img . '
' . $duration . '
' . $video['views_count'] . '
' . date("Y-m-d\TH:i:s", strtotime($video['created'])) . '+00:00
yes
' . (Video::isPublic($video['id']) ? "no" : "yes") . '
' . User::getNameIdentificationById($video['users_id']) . '
no
';
}
$xml .= ' ';
_error_log("siteMap: done ");
$newXML1 = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', '', $xml);
if (empty($newXML1)) {
_error_log("siteMap: pregreplace1 fail ");
$newXML1 = $xml;
}
if (!empty($advancedCustom->siteMapUTF8Fix)) {
$newXML2 = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $newXML1);
if (empty($newXML2)) {
_error_log("siteMap: pregreplace2 fail ");
$newXML2 = $newXML1;
}
$newXML3 = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $newXML2);
if (empty($newXML3)) {
_error_log("siteMap: pregreplace3 fail ");
$newXML3 = $newXML2;
}
$newXML4 = preg_replace('/[\x00-\x1F\x7F]/', '', $newXML3);
if (empty($newXML4)) {
_error_log("siteMap: pregreplace4 fail ");
$newXML4 = $newXML3;
}
$newXML5 = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $newXML4);
if (empty($newXML5)) {
_error_log("siteMap: pregreplace5 fail ");
$newXML5 = $newXML4;
}
} else {
$newXML5 = $newXML1;
}
return $newXML5;
}
function object_to_array($obj) {
//only process if it's an object or array being passed to the function
if (is_object($obj) || is_array($obj)) {
$ret = (array) $obj;
foreach ($ret as &$item) {
//recursively process EACH element regardless of type
$item = object_to_array($item);
}
return $ret;
}
//otherwise (i.e. for scalar values) return without modification
else {
return $obj;
}
}
function allowOrigin() {
global $global;
if (empty($_SERVER['HTTP_ORIGIN'])) {
$server = parse_url($global['webSiteRootURL']);
header('Access-Control-Allow-Origin: ' . $server["scheme"] . '://imasdk.googleapis.com');
} else {
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT");
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
}
function rrmdir($dir) {
global $global;
if ($dir == getVideosDir() . "" || $dir == "{$global['systemRootPath']}videos") {
return false;
}
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir . "/" . $object)) {
rrmdir($dir . "/" . $object);
} else {
unlink($dir . "/" . $object);
}
}
}
rmdir($dir);
}
}
/**
* You can now configure it on the configuration.php
* @return boolean
*/
function ddosProtection() {
global $global;
$maxCon = empty($global['ddosMaxConnections']) ? 40 : $global['ddosMaxConnections'];
$secondTimeout = empty($global['ddosSecondTimeout']) ? 5 : $global['ddosSecondTimeout'];
$whitelistedFiles = array(
'playlists.json.php',
'playlistsFromUserVideos.json.php',
'image404.php'
);
if (in_array(basename($_SERVER["SCRIPT_FILENAME"]), $whitelistedFiles)) {
return true;
}
$time = time();
if (!isset($_SESSION['bruteForceBlock']) || empty($_SESSION['bruteForceBlock'])) {
$_SESSION['bruteForceBlock'] = array();
$_SESSION['bruteForceBlock'][] = $time;
return true;
}
$_SESSION['bruteForceBlock'][] = $time;
//remove requests that are older than secondTimeout
foreach ($_SESSION['bruteForceBlock'] as $key => $request_time) {
if ($request_time < $time - $secondTimeout) {
unset($_SESSION['bruteForceBlock'][$key]);
}
}
//progressive timeout-> more requests, longer timeout
$active_connections = count($_SESSION['bruteForceBlock']);
$timeoutReal = ($active_connections / $maxCon) < 1 ? 0 : ($active_connections / $maxCon) * $secondTimeout;
if ($timeoutReal) {
_error_log("ddosProtection:: progressive timeout timeoutReal = ($timeoutReal) active_connections = ($active_connections) maxCon = ($maxCon) ", AVideoLog::$SECURITY);
}
sleep($timeoutReal);
//with strict mode, penalize "attacker" with sleep() above, log and then die
if ($global['strictDDOSprotection'] && $timeoutReal > 0) {
$str = "bruteForceBlock: maxCon: $maxCon => secondTimeout: $secondTimeout | IP: " . getRealIpAddr() . " | count:" . count($_SESSION['bruteForceBlock']);
_error_log($str);
die($str);
}
return true;
}
function getAdsLeaderBoardBigVideo() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardBigVideoMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardBigVideo->value);
}
}
}
function getAdsLeaderBoardTop() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardTopMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardTop->value);
}
}
}
function getAdsChannelLeaderBoardTop() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->channelLeaderBoardTopMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->channelLeaderBoardTop->value);
}
}
}
function getAdsLeaderBoardTop2() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardTopMobile2->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardTop2->value);
}
}
}
function getAdsLeaderBoardMiddle() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardMiddleMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardMiddle->value);
}
}
}
function getAdsLeaderBoardFooter() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardFooterMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardFooter->value);
}
}
}
function getAdsSideRectangle() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->sideRectangle->value);
} else {
return ADs::giveGoogleATimeout($ad->sideRectangle->value);
}
}
}
function isToHidePrivateVideos() {
$obj = AVideoPlugin::getObjectDataIfEnabled("Gallery");
if (!empty($obj)) {
return $obj->hidePrivateVideos;
}
$obj = AVideoPlugin::getObjectDataIfEnabled("YouPHPFlix2");
if (!empty($obj)) {
return $obj->hidePrivateVideos;
}
$obj = AVideoPlugin::getObjectDataIfEnabled("YouTube");
if (!empty($obj)) {
return $obj->hidePrivateVideos;
}
return false;
}
function convertImageToOG($source, $destination) {
if (!file_exists($destination)) {
$w = 200;
$h = 200;
$sizes = getimagesize($source);
if ($sizes[0] < $w || $sizes[1] < $h) {
$tmpDir = getTmpDir();
$fileConverted = $tmpDir . "_jpg_" . uniqid() . ".jpg";
convertImage($source, $fileConverted, 100);
im_resizeV2($fileConverted, $destination, $w, $h, 100);
unlink($fileConverted);
}
}
return $destination;
}
function convertImageToRoku($source, $destination) {
if (empty($source)) {
_error_log("convertImageToRoku: source image is empty");
return false;
}
$w = 1280;
$h = 720;
if (file_exists($destination)) {
$sizes = getimagesize($destination);
if ($sizes[0] < $w || $sizes[1] < $h) {
_error_log("convertImageToRoku: file is smaller " . json_encode($sizes));
unlink($destination);
}
}
if (!file_exists($destination)) {
try {
$tmpDir = getTmpDir();
$fileConverted = $tmpDir . "_jpg_" . uniqid() . ".jpg";
convertImage($source, $fileConverted, 100);
im_resizeV2($fileConverted, $destination, $w, $h, 100);
@unlink($fileConverted);
} catch (Exception $exc) {
_error_log("convertImageToRoku: " . $exc->getMessage());
return false;
}
}
return $destination;
}
function ogSite() {
global $global, $config;
include $global['systemRootPath'] . 'objects/functionogSite.php';
}
function getOpenGraph($videos_id) {
global $global, $config, $advancedCustom;
include $global['systemRootPath'] . 'objects/functiongetOpenGraph.php';
}
function getLdJson($videos_id) {
$cache = ObjectYPT::getCache("getLdJson{$videos_id}", 0);
if (empty($cache)) {
echo $cache;
}
global $global, $config;
echo "";
if (empty($videos_id)) {
echo "";
if (!empty($_GET['videoName'])) {
echo "";
$video = Video::getVideoFromCleanTitle($_GET['videoName']);
}
} else {
echo "";
$video = Video::getVideoLight($videos_id);
}
if (empty($video)) {
echo "";
return false;
}
$videos_id = $video['id'];
$source = Video::getSourceFile($video['filename']);
if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) {
$img = $source['url'];
$data = getimgsize($source['path']);
$imgw = $data[0];
$imgh = $data[1];
} elseif ($video['type'] == "audio") {
$img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg";
}
$type = 'video';
if ($video['type'] === 'pdf') {
$type = 'pdf';
}
if ($video['type'] === 'article') {
$type = 'article';
}
$images = Video::getImageFromFilename($video['filename'], $type);
if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') {
$img = $images->posterPortrait;
$data = getimgsize($images->posterPortraitPath);
$imgw = $data[0];
$imgh = $data[1];
} else {
$img = $images->poster;
}
$description = html2plainText(empty(trim($video['description'])) ? $video['title'] : $video['description']);
$duration = Video::getItemPropDuration($video['duration']);
if ($duration == "PT0H0M0S") {
$duration = "PT0H0M1S";
}
$output = '
';
ObjectYPT::setCache("getLdJson{$videos_id}", $output);
echo $output;
}
function getItemprop($videos_id) {
$cache = ObjectYPT::getCache("getItemprop{$videos_id}", 0);
if (empty($cache)) {
echo $cache;
}
global $global, $config;
echo "";
if (empty($videos_id)) {
echo "";
if (!empty($_GET['videoName'])) {
echo "";
$video = Video::getVideoFromCleanTitle($_GET['videoName']);
}
} else {
echo "";
$video = Video::getVideoLight($videos_id);
}
if (empty($video)) {
echo "";
return false;
}
$videos_id = $video['id'];
$source = Video::getSourceFile($video['filename']);
if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) {
$img = $source['url'];
$data = getimgsize($source['path']);
$imgw = $data[0];
$imgh = $data[1];
} elseif ($video['type'] == "audio") {
$img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg";
}
$type = 'video';
if ($video['type'] === 'pdf') {
$type = 'pdf';
}
if ($video['type'] === 'image') {
$type = 'image';
}
if ($video['type'] === 'zip') {
$type = 'zip';
}
if ($video['type'] === 'article') {
$type = 'article';
}
$images = Video::getImageFromFilename($video['filename'], $type);
if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') {
$img = $images->posterPortrait;
$data = getimgsize($images->posterPortraitPath);
$imgw = $data[0];
$imgh = $data[1];
} else {
$img = $images->poster;
}
$description = html2plainText(empty(trim($video['description'])) ? $video['title'] : $video['description']);
$duration = Video::getItemPropDuration($video['duration']);
if ($duration == "PT0H0M0S") {
$duration = "PT0H0M1S";
}
$output = '
';
ObjectYPT::setCache("getItemprop{$videos_id}", $output);
echo $output;
}
function getOS($user_agent = "") {
if (empty($user_agent)) {
$user_agent = @$_SERVER['HTTP_USER_AGENT'];
}
$os_platform = "Unknown OS Platform";
$os_array = array(
'/windows nt 10/i' => 'Windows 10',
'/windows nt 6.3/i' => 'Windows 8.1',
'/windows nt 6.2/i' => 'Windows 8',
'/windows nt 6.1/i' => 'Windows 7',
'/windows nt 6.0/i' => 'Windows Vista',
'/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
'/windows nt 5.1/i' => 'Windows XP',
'/windows xp/i' => 'Windows XP',
'/windows nt 5.0/i' => 'Windows 2000',
'/windows me/i' => 'Windows ME',
'/win98/i' => 'Windows 98',
'/win95/i' => 'Windows 95',
'/win16/i' => 'Windows 3.11',
'/macintosh|mac os x/i' => 'Mac OS X',
'/mac_powerpc/i' => 'Mac OS 9',
'/linux/i' => 'Linux',
'/ubuntu/i' => 'Ubuntu',
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
foreach ($os_array as $regex => $value) {
if (preg_match($regex, $user_agent)) {
$os_platform = $value;
}
}
return $os_platform;
}
function get_browser_name($user_agent = "") {
if (empty($user_agent)) {
$user_agent = @$_SERVER['HTTP_USER_AGENT'];
}
if (empty($user_agent)) {
return 'Unknow';
}
// Make case insensitive.
$t = strtolower($user_agent);
// If the string *starts* with the string, strpos returns 0 (i.e., FALSE). Do a ghetto hack and start with a space.
// "[strpos()] may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE."
// http://php.net/manual/en/function.strpos.php
$t = " " . $t;
// Humans / Regular Users
if (isAVideoStreamer($t)) {
return 'AVideo Mobile App';
} elseif ($url = isAVideoEncoder($t)) {
return 'AVideo Encoder ' . $url;
} elseif ($url = isAVideoStreamer($t)) {
return 'AVideo Streamer ' . $url;
} elseif (strpos($t, 'crkey')) {
return 'Chromecast';
} elseif (strpos($t, 'opera') || strpos($t, 'opr/')) {
return 'Opera';
} elseif (strpos($t, 'edge')) {
return 'Edge';
} elseif (strpos($t, 'chrome')) {
return 'Chrome';
} elseif (strpos($t, 'safari')) {
return 'Safari';
} elseif (strpos($t, 'firefox')) {
return 'Firefox';
} elseif (strpos($t, 'msie') || strpos($t, 'trident/7')) {
return 'Internet Explorer';
} elseif (strpos($t, 'applecoremedia')) {
return 'Native Apple Player';
}
// Search Engines
elseif (strpos($t, 'google')) {
return '[Bot] Googlebot';
} elseif (strpos($t, 'bing')) {
return '[Bot] Bingbot';
} elseif (strpos($t, 'slurp')) {
return '[Bot] Yahoo! Slurp';
} elseif (strpos($t, 'duckduckgo')) {
return '[Bot] DuckDuckBot';
} elseif (strpos($t, 'baidu')) {
return '[Bot] Baidu';
} elseif (strpos($t, 'yandex')) {
return '[Bot] Yandex';
} elseif (strpos($t, 'sogou')) {
return '[Bot] Sogou';
} elseif (strpos($t, 'exabot')) {
return '[Bot] Exabot';
} elseif (strpos($t, 'msn')) {
return '[Bot] MSN';
}
// Common Tools and Bots
elseif (strpos($t, 'mj12bot')) {
return '[Bot] Majestic';
} elseif (strpos($t, 'ahrefs')) {
return '[Bot] Ahrefs';
} elseif (strpos($t, 'semrush')) {
return '[Bot] SEMRush';
} elseif (strpos($t, 'rogerbot') || strpos($t, 'dotbot')) {
return '[Bot] Moz or OpenSiteExplorer';
} elseif (strpos($t, 'frog') || strpos($t, 'screaming')) {
return '[Bot] Screaming Frog';
}
// Miscellaneous
elseif (strpos($t, 'facebook')) {
return '[Bot] Facebook';
} elseif (strpos($t, 'pinterest')) {
return '[Bot] Pinterest';
}
// Check for strings commonly used in bot user agents
elseif (strpos($t, 'crawler') || strpos($t, 'api') ||
strpos($t, 'spider') || strpos($t, 'http') ||
strpos($t, 'bot') || strpos($t, 'archive') ||
strpos($t, 'info') || strpos($t, 'data')) {
return '[Bot] Other';
}
//_error_log("Unknow user agent ($t) IP=" . getRealIpAddr() . " URI=" . getRequestURI());
return 'Other (Unknown)';
}
/**
* Due some error on old chrome browsers (version < 70) on decrypt HLS keys with the videojs versions greater then 7.9.7
* we need to detect the chrome browser and load an older version
*
*/
function isOldChromeVersion() {
$global;
if (empty($_SERVER['HTTP_USER_AGENT'])) {
return false;
}
if (!empty($global['forceOldChrome'])) {
return true;
}
if (preg_match('/Chrome\/([0-9.]+)/i', $_SERVER['HTTP_USER_AGENT'], $matches)) {
return version_compare($matches[1], '80', '<=');
}
return false;
}
function TimeLogStart($name) {
global $global;
if (!empty($global['noDebug'])) {
return false;
}
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
if (empty($global['start']) || !is_array($global['start'])) {
$global['start'] = array();
}
$global['start'][$name] = $time;
}
function TimeLogEnd($name, $line, $TimeLogLimit = 0.7) {
global $global;
if (!empty($global['noDebug'])) {
return false;
}
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $global['start'][$name]), 4);
if ($total_time > $TimeLogLimit) {
_error_log("Warning: Slow process detected [{$name}] On Line {$line} takes {$total_time} seconds to complete, Limit ({$TimeLogLimit}). {$_SERVER["SCRIPT_FILENAME"]}");
}
TimeLogStart($name);
}
class AVideoLog {
public static $DEBUG = 0;
public static $WARNING = 1;
public static $ERROR = 2;
public static $SECURITY = 3;
public static $SOCKET = 4;
}
function _error_log($message, $type = 0, $doNotRepeat = false) {
if (empty($doNotRepeat)) {
// do not log it too many times when you are using HLS format, other wise it will fill the log file with the same error
$doNotRepeat = preg_match("/hls.php$/", $_SERVER['SCRIPT_NAME']);
}
if ($doNotRepeat) {
return false;
}
global $global;
if (!empty($global['noDebug']) && $type == 0) {
return false;
}
if (!is_string($message)) {
$message = json_encode($message);
}
$prefix = "AVideoLog::";
switch ($type) {
case AVideoLog::$DEBUG:
$prefix .= "DEBUG: ";
break;
case AVideoLog::$WARNING:
$prefix .= "WARNING: ";
break;
case AVideoLog::$ERROR:
$prefix .= "ERROR: ";
break;
case AVideoLog::$SECURITY:
$prefix .= "SECURITY: ";
break;
case AVideoLog::$SOCKET:
$prefix .= "SOCKET: ";
break;
}
error_log($prefix . $message . " SCRIPT_NAME: {$_SERVER['SCRIPT_NAME']}");
}
function postVariables($url, $array) {
if (!$url || !is_string($url) || !preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)) {
return false;
}
$array = object_to_array($array);
$ch = curl_init($url);
@curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
@curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// execute!
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// close the connection, release resources used
curl_close($ch);
if ($httpcode == 200) {
return true;
}
return $httpcode;
}
function _session_start(array $options = array()) {
try {
if (session_status() == PHP_SESSION_NONE) {
return @session_start($options);
}
} catch (Exception $exc) {
_error_log("_session_start: " . $exc->getTraceAsString());
return false;
}
}
function _mysql_connect() {
global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort;
if (is_object($global['mysqli']) && empty(@$global['mysqli']->ping())) {
try {
$global['mysqli'] = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, @$mysqlPort);
if (!empty($global['mysqli_charset'])) {
$global['mysqli']->set_charset($global['mysqli_charset']);
}
} catch (Exception $exc) {
_error_log($exc->getTraceAsString());
return false;
}
}
}
function _mysql_close() {
global $global;
if (is_object($global['mysqli']) && !empty(@$global['mysqli']->ping())) {
@$global['mysqli']->close();
}
}
function remove_utf8_bom($text) {
if (strlen($text) > 1000000) {
return $text;
}
$bom = pack('H*', 'EFBBBF');
$text = preg_replace("/^$bom/", '', $text);
return $text;
}
function getCacheDir() {
$p = AVideoPlugin::loadPlugin("Cache");
return $p->getCacheDir();
}
function clearCache() {
global $global;
$dir = getVideosDir() . "cache/";
if (!empty($_GET['FirstPage'])) {
$dir .= "firstPage/";
}
rrmdir($dir);
$dir = getCacheDir();
if (!empty($_GET['FirstPage'])) {
$dir .= "firstPage/";
}
rrmdir($dir);
ObjectYPT::deleteCache("getEncoderURL");
}
function getUsageFromFilename($filename, $dir = "") {
global $global;
if (!empty($global['getUsageFromFilename'])) { // manually add this variable in your configuration.php file to not scan your video usage
return 0;
}
if (empty($dir)) {
$dir = getVideosDir() . "";
}
$pos = strrpos($dir, '/');
$dir .= (($pos === false) ? "/" : "");
$totalSize = 0;
_error_log("getUsageFromFilename: start {$dir}{$filename}");
//$files = glob("{$dir}{$filename}*");
$files = globVideosDir($filename);
session_write_close();
$filesProcessed = array();
if (empty($files)) {
_error_log("getUsageFromFilename: we did not find any file for {$dir}{$filename}, we will create a fake one");
file_put_contents("{$dir}{$filename}.notfound", time());
$totalSize = 10;
} else {
foreach ($files as $f) {
if (strpos($f, '.size.lock') !== false) {
continue;
}
if (is_dir($f)) {
_error_log("getUsageFromFilename: {$f} is Dir");
$dirSize = getDirSize($f);
$totalSize += $dirSize;
if ($dirSize < 10000 && AVideoPlugin::isEnabledByName('YPTStorage')) {
// probably the HLS file is hosted on the YPTStorage
$info = YPTStorage::getFileInfo($filename);
if (!empty($info->size)) {
$totalSize += $info->size;
}
}
} elseif (is_file($f)) {
$filesize = filesize($f);
if ($filesize < 20) { // that means it is a dummy file
$lockFile = $f . ".size.lock";
if (!file_exists($lockFile) || (time() - 600) > filemtime($lockFile)) {
file_put_contents($lockFile, time());
_error_log("getUsageFromFilename: {$f} is Dummy file ({$filesize})");
$aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3');
//$bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2');
if (!empty($aws_s3)) {
_error_log("getUsageFromFilename: Get from S3");
$filesize += $aws_s3->getFilesize($filename);
} elseif (!empty($bb_b2)) {
// TODO
} else {
$urls = Video::getVideosPaths($filename, true);
_error_log("getUsageFromFilename: Paths " . json_encode($urls));
if (!empty($urls["m3u8"]['url'])) {
$filesize += getUsageFromURL($urls["m3u8"]['url']);
}
if (!empty($urls['mp4'])) {
foreach ($urls['mp4'] as $mp4) {
if (in_array($mp4, $filesProcessed)) {
continue;
}
$filesProcessed[] = $mp4;
$filesize += getUsageFromURL($mp4);
}
}
if (!empty($urls['webm'])) {
foreach ($urls['webm'] as $mp4) {
if (in_array($mp4, $filesProcessed)) {
continue;
}
$filesProcessed[] = $mp4;
$filesize += getUsageFromURL($mp4);
}
}
if (!empty($urls["pdf"]['url'])) {
$filesize += getUsageFromURL($urls["pdf"]['url']);
}
if (!empty($urls["image"]['url'])) {
$filesize += getUsageFromURL($urls["image"]['url']);
}
if (!empty($urls["zip"]['url'])) {
$filesize += getUsageFromURL($urls["zip"]['url']);
}
if (!empty($urls["mp3"]['url'])) {
$filesize += getUsageFromURL($urls["mp3"]['url']);
}
}
unlink($lockFile);
}
} else {
_error_log("getUsageFromFilename: {$f} is File ({$filesize})");
}
$totalSize += $filesize;
}
}
}
return $totalSize;
}
/**
* Returns the size of a file without downloading it, or -1 if the file
* size could not be determined.
*
* @param $url - The location of the remote file to download. Cannot
* be null or empty.
*
* @return The size of the file referenced by $url, or false if the size
* could not be determined.
*/
function getUsageFromURL($url) {
global $global;
if (!empty($global['doNotGetUsageFromURL'])) { // manually add this variable in your configuration.php file to not scan your video usage
return 0;
}
_error_log("getUsageFromURL: start ({$url})");
// Assume failure.
$result = false;
$curl = curl_init($url);
_error_log("getUsageFromURL: curl_init ");
try {
// Issue a HEAD request and follow any redirects.
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
//curl_setopt($curl, CURLOPT_USERAGENT, get_user_agent_string());
$data = curl_exec($curl);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
_error_log("getUsageFromURL: ERROR " . $exc->getMessage());
_error_log("getUsageFromURL: ERROR " . curl_errno($curl));
_error_log("getUsageFromURL: ERROR " . curl_error($curl));
}
if ($data) {
_error_log("getUsageFromURL: response header " . $data);
$content_length = "unknown";
$status = "unknown";
if (preg_match("/^HTTP\/1\.[01] (\d\d\d)/", $data, $matches)) {
$status = (int) $matches[1];
}
if (preg_match("/Content-Length: (\d+)/", $data, $matches)) {
$content_length = (int) $matches[1];
}
// http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
if ($status == 200 || ($status > 300 && $status <= 308)) {
$result = $content_length;
}
} else {
_error_log("getUsageFromURL: ERROR no response data " . curl_error($curl));
}
curl_close($curl);
return (int) $result;
}
function getDirSize($dir) {
_error_log("getDirSize: start {$dir}");
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
return foldersize($dir);
} else {
$command = "du -sb {$dir}";
exec($command . " < /dev/null 2>&1", $output, $return_val);
if ($return_val !== 0) {
_error_log("getDirSize: ERROR ON Command {$command}");
return 0;
} else {
if (!empty($output[0])) {
preg_match("/^([0-9]+).*/", $output[0], $matches);
}
if (!empty($matches[1])) {
_error_log("getDirSize: found {$matches[1]} from - {$output[0]}");
return intval($matches[1]);
}
_error_log("getDirSize: ERROR on pregmatch {$output[0]}");
return 0;
}
}
}
function foldersize($path) {
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/') . '/';
foreach ($files as $t) {
if ($t <> "." && $t <> "..") {
$currentFile = $cleanPath . $t;
if (is_dir($currentFile)) {
$size = foldersize($currentFile);
$total_size += $size;
} else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}
return $total_size;
}
function getDiskUsage() {
global $global;
$dir = getVideosDir() . "";
$obj = new stdClass();
$obj->disk_free_space = disk_free_space($dir);
$obj->disk_total_space = disk_total_space($dir);
$obj->videos_dir = getDirSize($dir);
$obj->disk_used = $obj->disk_total_space - $obj->disk_free_space;
$obj->disk_used_by_other = $obj->disk_used - $obj->videos_dir;
$obj->disk_free_space_human = humanFileSize($obj->disk_free_space);
$obj->disk_total_space_human = humanFileSize($obj->disk_total_space);
$obj->videos_dir_human = humanFileSize($obj->videos_dir);
$obj->disk_used_human = humanFileSize($obj->disk_used);
$obj->disk_used_by_other_human = humanFileSize($obj->disk_used_by_other);
// percentage of disk used
$obj->disk_used_percentage = sprintf('%.2f', ($obj->disk_used / $obj->disk_total_space) * 100);
$obj->videos_dir_used_percentage = sprintf('%.2f', ($obj->videos_dir / $obj->disk_total_space) * 100);
$obj->disk_free_space_percentage = sprintf('%.2f', ($obj->disk_free_space / $obj->disk_total_space) * 100);
return $obj;
}
function unsetSearch() {
unset($_GET['searchPhrase']);
unset($_POST['searchPhrase']);
unset($_GET['search']);
unset($_GET['q']);
}
function encrypt_decrypt($string, $action) {
global $global;
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = $global['systemRootPath'];
while (strlen($secret_iv) < 16) {
$secret_iv .= $global['systemRootPath'];
}
// hash
$key = hash('sha256', $global['salt']);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ($action == 'encrypt') {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} elseif ($action == 'decrypt') {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
function compressString($string) {
if (function_exists("gzdeflate")) {
$string = gzdeflate($string, 9);
}
return $string;
}
function decompressString($string) {
if (function_exists("gzinflate")) {
$string = gzinflate($string);
}
return $string;
}
function encryptString($string) {
if (is_object($string)) {
$string = json_encode($string);
}
return encrypt_decrypt($string, 'encrypt');
}
function decryptString($string) {
return encrypt_decrypt($string, 'decrypt');
}
function getToken($timeout = 0, $salt = "") {
global $global;
$obj = new stdClass();
$obj->salt = $global['salt'] . $salt;
if (!empty($timeout)) {
$obj->time = time();
$obj->timeout = $obj->time + $timeout;
} else {
$obj->time = strtotime("Today 00:00:00");
$obj->timeout = strtotime("Today 23:59:59");
$obj->timeout += cacheExpirationTime();
}
$strObj = json_encode($obj);
//_error_log("Token created: {$strObj}");
return encryptString($strObj);
}
function isTokenValid($token, $salt = "") {
return verifyToken($token, $salt);
}
function verifyToken($token, $salt = "") {
global $global;
$obj = json_decode(decryptString($token));
if (empty($obj)) {
_error_log("verifyToken invalid token");
return false;
}
if ($obj->salt !== $global['salt'] . $salt) {
_error_log("verifyToken salt fail");
return false;
}
$time = time();
if (!($time >= $obj->time && $time <= $obj->timeout)) {
_error_log("verifyToken token timout time = $time; obj->time = $obj->time; obj->timeout = $obj->timeout");
return false;
}
return true;
}
class YPTvideoObject {
public $id;
public $title;
public $description;
public $thumbnails;
public $channelTitle;
public $videoLink;
public function __construct($id, $title, $description, $thumbnails, $channelTitle, $videoLink) {
$this->id = $id;
$this->title = $title;
$this->description = $description;
$this->thumbnails = $thumbnails;
$this->channelTitle = $channelTitle;
$this->videoLink = $videoLink;
}
}
function isToShowDuration($type) {
$notShowTo = array('pdf', 'article', 'serie', 'zip', 'image', 'live', 'livelinks');
if (in_array($type, $notShowTo)) {
return false;
} else {
return true;
}
}
function _dieAndLogObject($obj, $prefix = "") {
$objString = json_encode($obj);
_error_log($prefix . $objString);
die($objString);
}
function isAVideoPlayer() {
if (isVideo()) {
return true;
}
return false;
}
function isVideo() {
global $isModeYouTube;
return !empty($isModeYouTube) || isPlayList() || isEmbed() || isLive();
}
function isAudio() {
global $isAudio;
return !empty($isAudio);
}
function isSerie() {
return isPlayList();
}
function isPlayList() {
global $isPlayList, $isSerie;
return !empty($isSerie) || !empty($isPlayList);
}
function isChannel() {
global $isChannel;
if (!empty($isChannel) && !isVideo()) {
$user_id = 0;
if (empty($_GET['channelName'])) {
if (User::isLogged()) {
$user_id = User::getId();
} else {
return false;
}
} else {
$_GET['channelName'] = xss_esc($_GET['channelName']);
$user = User::getChannelOwner($_GET['channelName']);
if (!empty($user)) {
$user_id = $user['id'];
} else {
$user_id = $_GET['channelName'];
}
}
return $user_id;
}
return false;
}
function isEmbed() {
global $isEmbed;
return !empty($isEmbed);
}
function isLive() {
global $isLive;
if (!empty($isLive)) {
$live = getLiveKey();
if(empty($live)){
$live = array('key'=>false, 'live_servers_id'=>false);
}
$live['liveLink'] = isLiveLink();
return $live;
} else {
return false;
}
}
function isLiveLink() {
global $isLiveLink;
if (!empty($isLiveLink)) {
return $isLiveLink;
} else {
return false;
}
}
function getLiveKey() {
global $getLiveKey;
if (empty($getLiveKey)) {
return false;
}
return $getLiveKey;
}
function setLiveKey($key, $live_servers_id) {
global $getLiveKey;
$getLiveKey = array('key' => $key, 'live_servers_id' => intval($live_servers_id));
return $getLiveKey;
}
function isVideoPlayerHasProgressBar() {
if (isLive()) {
$obj = AVideoPlugin::getObjectData('Live');
if (empty($obj->disableDVR)) {
return true;
}
} elseif (isAVideoPlayer()) {
return true;
}
return false;
}
function isHLS() {
global $video, $global;
if (isLive()) {
return true;
} elseif (!empty($video) && $video['type'] == 'video' && file_exists(getVideosDir() . "{$video['filename']}/index.m3u8")) {
return true;
}
return false;
}
function getRedirectUri() {
if (!empty($_GET['redirectUri'])) {
return $_GET['redirectUri'];
}
if (!empty($_SERVER["HTTP_REFERER"])) {
return $_SERVER["HTTP_REFERER"];
}
return getRequestURI();
}
function getRequestURI() {
if (empty($_SERVER['REQUEST_URI'])) {
return "";
}
return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
}
function getSelfURI() {
if (empty($_SERVER['PHP_SELF']) || empty($_SERVER['HTTP_HOST'])) {
return "";
}
$queryStringWithoutError = preg_replace("/error=[^&]*/", "", @$_SERVER['QUERY_STRING']);
$phpselfWithoutIndex = preg_replace("/index.php/", "", @$_SERVER['PHP_SELF']);
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$phpselfWithoutIndex?$queryStringWithoutError";
$url = rtrim($url, '?');
return $url;
}
function isSameVideoAsSelfURI($url) {
return URLsAreSameVideo($url, getSelfURI());
}
function URLsAreSameVideo($url1, $url2) {
$videos_id1 = getVideoIDFromURL($url1);
$videos_id2 = getVideoIDFromURL($url2);
if (empty($videos_id1) || empty($videos_id2)) {
return false;
}
return $videos_id1 === $videos_id2;
}
function getVideos_id() {
if (isVideo()) {
return getVideoIDFromURL(getSelfURI());
}
return false;
}
function getVideoIDFromURL($url) {
if (preg_match("/v=([0-9]+)/", $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/video\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/videoEmbed\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/v\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/vEmbed\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/article\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/articleEmbed\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if(AVideoPlugin::isEnabledByName('PlayLists')){
if (preg_match('/player.php\?playlists_id=([0-9]+)/', $url, $matches)) {
$serie_playlists_id = intval($matches[1]);
$video = PlayLists::isPlayListASerie($serie_playlists_id);
if($video){
return $video['id'];
}
}
}
return false;
}
function getBackURL() {
global $global;
$backURL = getRedirectUri();
if (empty($backURL)) {
$backURL = getRequestURI();
}
if (isSameVideoAsSelfURI($backURL)) {
$backURL = getHomeURL();
}
return $backURL;
}
function getHomeURL() {
global $global, $advancedCustomUser, $advancedCustom;
if (isValidURL($advancedCustomUser->afterLoginGoToURL)) {
return $advancedCustomUser->afterLoginGoToURL;
} elseif (isValidURL($advancedCustom->logoMenuBarURL) && isSameDomainAsMyAVideo($advancedCustom->logoMenuBarURL)) {
return $advancedCustom->logoMenuBarURL;
}
return $global['webSiteRootURL'];
}
function isValidURL($url) {
//var_dump(empty($url), !is_string($url), preg_match("/^http.*/", $url), filter_var($url, FILTER_VALIDATE_URL));
if (empty($url) || !is_string($url)) {
return false;
}
if (preg_match("/^http.*/", $url) && filter_var($url, FILTER_VALIDATE_URL)) {
return true;
}
return false;
}
function hasLastSlash($word) {
return substr($word, -1) === '/';
}
function addLastSlash($word) {
return $word . (hasLastSlash($word) ? "" : "/");
}
function URLHasLastSlash() {
return hasLastSlash($_SERVER["REQUEST_URI"]);
}
function ucname($str) {
$str = ucwords(strtolower($str));
foreach (array('\'', '-') as $delim) {
if (strpos($str, $delim) !== false) {
$str = implode($delim, array_map('ucfirst', explode($delim, $str)));
}
}
return $str;
}
function sanitize_input($input) {
return htmlentities(strip_tags($input));
}
function sanitize_array_item(&$item, $key) {
$item = sanitize_input($item);
}
function getSEOComplement($parameters = array()) {
global $config;
$allowedTypes = isset($parameters["allowedTypes"]) ? $parameters["allowedTypes"] : null;
$addAutoPrefix = isset($parameters["addAutoPrefix"]) ? $parameters["addAutoPrefix"] : true;
$addCategory = isset($parameters["addCategory"]) ? $parameters["addCategory"] : true;
$parts = array();
if (!empty($_GET['error'])) {
array_push($parts, __("Error"));
}
if ($addCategory && !empty($_GET['catName'])) {
array_push($parts, $_GET['catName']);
}
if (!empty($_GET['channelName'])) {
array_push($parts, $_GET['channelName']);
}
if (!empty($_GET['type'])) {
$type = $_GET['type'];
if (empty($allowedTypes) || in_array(strtolower($type), $allowedTypes)) {
array_push($parts, __(ucname($type)));
}
}
if (!empty($_GET['showOnly'])) {
array_push($parts, $_GET['showOnly']);
}
if (!empty($_GET['page'])) {
$page = intval($_GET['page']);
if ($page > 1) {
array_push($parts, sprintf(__("Page %d"), $page));
}
}
// Cleaning all entries in the $parts array
array_walk($parts, 'sanitize_array_item');
$txt = implode($config->getPageTitleSeparator(), $parts);
$txt = (!empty($txt) && $addAutoPrefix ? $config->getPageTitleSeparator() : "") . $txt;
return $txt;
}
function getCurrentPage() {
if (!empty($_REQUEST['current'])) {
return intval($_REQUEST['current']);
} elseif (!empty($_POST['current'])) {
return intval($_POST['current']);
} elseif (!empty($_GET['current'])) {
return intval($_GET['current']);
} elseif (isset($_GET['start']) && isset($_GET['length'])) { // for the bootgrid
$start = intval($_GET['start']);
$length = intval($_GET['length']);
if (!empty($start) && !empty($length)) {
return floor($start / $length) + 1;
}
}
return 1;
}
function getRowCount($default = 1000) {
global $global;
if (!empty($_REQUEST['rowCount'])) {
$defaultN = intval($_REQUEST['rowCount']);
} elseif (!empty($_POST['rowCount'])) {
$defaultN = intval($_POST['rowCount']);
} elseif (!empty($_GET['rowCount'])) {
$defaultN = intval($_GET['rowCount']);
} elseif (!empty($_REQUEST['length'])) {
$defaultN = intval($_REQUEST['length']);
} elseif (!empty($_POST['length'])) {
$defaultN = intval($_POST['length']);
} elseif (!empty($_GET['length'])) {
$defaultN = intval($_GET['length']);
} elseif (!empty($global['rowCount'])) {
$defaultN = intval($global['rowCount']);
}
return (!empty($defaultN) && $defaultN > 0) ? $defaultN : $default;
}
function getSearchVar() {
if (!empty($_REQUEST['search'])) {
return $_REQUEST['search'];
} elseif (!empty($_REQUEST['q'])) {
return $_REQUEST['q'];
}
if (!empty($_REQUEST['searchPhrase'])) {
return $_REQUEST['searchPhrase'];
} elseif (!empty($_REQUEST['search']['value'])) {
return $_REQUEST['search']['value'];
}
return "";
}
$cleanSearchHistory = "";
function cleanSearchVar() {
global $cleanSearchHistory;
$search = getSearchVar();
if (!empty($search)) {
$cleanSearchHistory = $search;
}
$searchIdex = array('q', 'searchPhrase', 'search');
foreach ($searchIdex as $value) {
unset($_REQUEST[$value]);
unset($_POST[$value]);
unset($_GET[$value]);
}
}
function reloadSearchVar() {
global $cleanSearchHistory;
$_REQUEST['search'] = $cleanSearchHistory;
if (empty($_GET['search'])) {
$_GET['search'] = $cleanSearchHistory;
}
if (empty($_POST['search'])) {
$_POST['search'] = $cleanSearchHistory;
}
}
function wget($url, $filename, $debug = false) {
if (empty($url) || $url == "php://input" || !preg_match("/^http/", $url)) {
return false;
}
if (wgetIsLocked($url)) {
if ($debug) {
_error_log("wget: ERROR the url is already downloading $url, $filename");
}
return false;
}
wgetLock($url);
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$content = @file_get_contents($url);
if (!empty($content) && file_put_contents($filename, $content) > 100) {
wgetRemoveLock($url);
return true;
}
wgetRemoveLock($url);
return false;
}
$cmd = "wget --tries=1 {$url} -O {$filename} --no-check-certificate";
if ($debug) {
_error_log("wget Start ({$cmd}) ");
}
//echo $cmd;
exec($cmd);
wgetRemoveLock($url);
if (!file_exists($filename)) {
_error_log("wget: ERROR the url does not download $url, $filename");
return false;
}
if (empty(filesize($filename))) {
_error_log("wget: ERROR the url download but is empty $url, $filename");
return true;
}
return false;
}
function wgetLockFile($url) {
return getTmpDir("YPTWget") . md5($url) . ".lock";
}
function wgetLock($url) {
$file = wgetLockFile($url);
return file_put_contents($file, time() . PHP_EOL, FILE_APPEND | LOCK_EX);
}
function wgetRemoveLock($url) {
$filename = wgetLockFile($url);
if (!file_exists($filename)) {
return false;
}
return unlink($filename);
}
function getLockFile($name) {
return getTmpDir("YPTLockFile") . md5($name) . ".lock";
}
function setLock($name) {
$file = getLockFile($name);
return file_put_contents($file, time());
}
function isLock($name, $timeout = 60) {
$file = getLockFile($name);
if (file_exists($file)) {
$time = intval(file_get_contents($file));
if ($time + $timeout < time()) {
return false;
}
}
}
function removeLock($name) {
$filename = getLockFile($name);
if (!file_exists($filename)) {
return false;
}
return unlink($filename);
}
function wgetIsLocked($url) {
$filename = wgetLockFile($url);
if (!file_exists($filename)) {
return false;
}
$time = intval(file_get_contents($filename));
if (time() - $time > 36000) { // more then 10 hours
unlink($filename);
return false;
}
return true;
}
// due the some OS gives a fake is_writable response
function isWritable($dir) {
$dir = rtrim($dir, '/') . '/';
$file = $dir . uniqid();
$result = false;
$time = time();
if (@file_put_contents($file, $time)) {
if ($fileTime = @file_get_contents($file)) {
if ($fileTime == $time) {
$result = true;
}
}
}
@unlink($file);
return $result;
}
function _isWritable($dir) {
if (!isWritable($dir)) {
return false;
}
$tmpFile = "{$dir}" . uniqid();
$bytes = @file_put_contents($tmpFile, time());
@unlink($tmpFile);
return !empty($bytes);
}
function getTmpDir($subdir = "") {
global $global;
if (empty($_SESSION['getTmpDir'])) {
$_SESSION['getTmpDir'] = array();
}
if (empty($_SESSION['getTmpDir'][$subdir . "_"])) {
$tmpDir = sys_get_temp_dir();
if (empty($tmpDir) || !_isWritable($tmpDir)) {
$tmpDir = getVideosDir() . "cache/";
}
$tmpDir = rtrim($tmpDir, '/') . '/';
$tmpDir = "{$tmpDir}{$subdir}";
$tmpDir = rtrim($tmpDir, '/') . '/';
if (!is_dir($tmpDir)) {
mkdir($tmpDir, 0755, true);
}
_session_start();
$_SESSION['getTmpDir'][$subdir . "_"] = $tmpDir;
} else {
$tmpDir = $_SESSION['getTmpDir'][$subdir . "_"];
}
return $tmpDir;
}
function getTmpFile() {
return getTmpDir("tmpFiles") . uniqid();
}
function getMySQLDate() {
global $global;
$sql = "SELECT now() as time FROM configurations LIMIT 1";
// I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about
$res = sqlDAL::readSql($sql);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data['time'];
} else {
$row = false;
}
return $row;
}
function _file_put_contents($filename, $data, $flags = 0, $context = null) {
make_path($filename);
return file_put_contents($filename, $data, $flags, $context);
}
function html2plainText($html) {
$text = strip_tags($html);
$text = str_replace(array('\\', "\n", "\r", '"'), array('', ' ', ' ', ''), trim($text));
return $text;
}
function getInputPassword($id, $attributes = 'class="form-control"', $paceholder = '') {
if (empty($paceholder)) {
$paceholder = __("Password");
}
?>
>
>
data-toggle="tooltip" data-placement="left" title="">
" . PHP_EOL;
} else {
return __LINE__;
}
$object = object_to_array($object);
$json = json_encode($object);
if (json_last_error()) {
echo "Error 1 Found after array conversion: " . json_last_error_msg() . " " . PHP_EOL;
} else {
return __LINE__;
}
$json = json_encode($object, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
echo "Error 1 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . " " . PHP_EOL;
} else {
return __LINE__;
}
$objectEncoded = $object;
array_walk_recursive($objectEncoded, function (&$item) {
if (is_string($item)) {
$item = utf8_encode($item);
}
});
$json = json_encode($objectEncoded);
if (json_last_error()) {
echo "Error 2 Found after array conversion: " . json_last_error_msg() . " " . PHP_EOL;
} else {
return __LINE__;
}
$json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . " " . PHP_EOL;
} else {
return __LINE__;
}
$objectDecoded = $object;
array_walk_recursive($objectDecoded, function (&$item) {
if (is_string($item)) {
$item = utf8_decode($item);
}
});
$json = json_encode($objectDecoded);
if (json_last_error()) {
echo "Error 2 Found after array conversion: " . json_last_error_msg() . " " . PHP_EOL;
} else {
return __LINE__;
}
$json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . " " . PHP_EOL;
} else {
return __LINE__;
}
return false;
}
function _json_encode($object) {
if (empty($object)) {
return false;
}
$json = json_encode($object);
if (json_last_error()) {
_error_log("_json_encode: Error 1 Found: " . json_last_error_msg());
$object = object_to_array($object);
$json = json_encode($object);
if (json_last_error()) {
_error_log("_json_encode: Error 2 Found: " . json_last_error_msg());
$json = json_encode($object, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
_error_log("_json_encode: Error 3 Found: " . json_last_error_msg());
$objectEncoded = $object;
array_walk_recursive($objectEncoded, function (&$item) {
if (is_string($item)) {
$item = utf8_encode($item);
}
});
$json = json_encode($objectEncoded);
if (json_last_error()) {
_error_log("_json_encode: Error 4 Found: " . json_last_error_msg());
$json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
_error_log("_json_encode: Error 5 Found: " . json_last_error_msg());
$objectDecoded = $object;
array_walk_recursive($objectDecoded, function (&$item) {
if (is_string($item)) {
$item = utf8_decode($item);
}
});
$json = json_encode($objectDecoded);
if (json_last_error()) {
_error_log("_json_encode: Error 6 Found: " . json_last_error_msg());
$json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
_error_log("_json_encode: Error 7 Found: " . json_last_error_msg());
}
}
}
}
}
}
}
return $json;
}
// this will make sure the strring will fits in the database field
function _substr($string, $start, $length = null) {
// make sure the name is not chunked in case of multibyte string
if (function_exists("mb_strcut")) {
return mb_strcut($string, $start, $length, "UTF-8");
} else {
return substr($string, $start, $length);
}
}
function getPagination($total, $page = 0, $link = "", $maxVisible = 10, $infinityScrollGetFromSelector = "", $infinityScrollAppendIntoSelector = "") {
global $global, $advancedCustom;
if ($total < 2) {
return "";
}
$uid = md5($link);
if ($total < $maxVisible) {
$maxVisible = $total;
}
if (empty($link)) {
$link = getSelfURI();
if (preg_match("/(current=[0-9]+)/i", $link, $match)) {
$link = str_replace($match[1], "current={page}", $link);
} else {
$link .= (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'current={page}';
}
}
if (empty($page)) {
$page = getCurrentPage();
}
$class = "";
if (!empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector)) {
$class = "infiniteScrollPagination{$uid} hidden";
}
$pag = ' ';
if (!empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector)) {
$content = file_get_contents($global['systemRootPath'] . 'objects/functiongetPagination.php');
$pag .= str_replace(
array('$uid', '$webSiteRootURL', '$infinityScrollGetFromSelector', '$infinityScrollAppendIntoSelector'),
array($uid, $global['webSiteRootURL'], $infinityScrollGetFromSelector, $infinityScrollAppendIntoSelector),
$content
);
}
return $pag;
}
function getShareMenu($title, $permaLink, $URLFriendly, $embedURL, $img, $class = "row bgWhite list-group-item menusDiv") {
global $global, $advancedCustom;
include $global['systemRootPath'] . 'objects/functiongetShareMenu.php';
}
function getSharePopupButton($videos_id, $url = "", $title = "") {
global $global, $advancedCustom;
if ($advancedCustom->disableShareOnly || $advancedCustom->disableShareAndPlaylist) {
return false;
}
$video['id'] = $videos_id;
include $global['systemRootPath'] . 'view/include/socialModal.php';
}
function forbiddenPage($message, $logMessage = false) {
global $global;
$_REQUEST['403ErrorMsg'] = $message;
if ($logMessage) {
_error_log($message);
}
include $global['systemRootPath'] . 'view/forbiddenPage.php';
exit;
}
define('E_FATAL', E_ERROR | E_USER_ERROR | E_PARSE | E_CORE_ERROR |
E_COMPILE_ERROR | E_RECOVERABLE_ERROR);
if (!isCommandLineInterface()) {
register_shutdown_function('avidoeShutdown');
}
function avidoeShutdown() {
global $global;
$error = error_get_last();
if ($error && ($error['type'] & E_FATAL)) {
_error_log($error, AVideoLog::$ERROR);
include $global['systemRootPath'] . 'view/maintanance.html';
exit;
}
}
function videoNotFound($message, $logMessage = false) {
global $global;
$_REQUEST['404ErrorMsg'] = $message;
if ($logMessage) {
_error_log($message);
}
include $global['systemRootPath'] . 'view/videoNotFound.php';
exit;
}
function isForbidden() {
global $global;
if (!empty($global['isForbidden'])) {
return true;
}
return false;
}
function diskUsageBars() {
global $global;
ob_start();
include $global['systemRootPath'] . 'objects/functiondiskUsageBars.php';
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
function getDomain() {
global $global;
if (empty($_SERVER['HTTP_HOST'])) {
$parse = parse_url($global['webSiteRootURL']);
return $parse['host'];
}
$domain = $_SERVER['HTTP_HOST'];
$domain = str_replace("www.", "", $domain);
$domain = preg_match("/^\..+/", $domain) ? ltrim($domain, '.') : $domain;
return $domain;
}
/**
* It's separated by time, version, clock_seq_hi, clock_seq_lo, node, as indicated in the followoing rfc.
*
* From the IETF RFC4122:
* 8-4-4-4-12
* @return string
*/
function getDeviceID($useRandomString = true) {
$ip = getRealIpAddr();
if (empty($_SERVER['HTTP_USER_AGENT'])) {
return "unknowDevice-{$ip}";
}
if (empty($useRandomString)) {
$device = get_browser_name() . '-' . getOS() . '-' . $ip . '-' . md5($_SERVER['HTTP_USER_AGENT']);
$device = str_replace(
array('[', ']', ' '),
array('', '', '_'), $device);
if (User::isLogged()) {
$device .= '-' . User::getId();
}
return $device;
}
$cookieName = "yptDeviceID";
if (empty($_COOKIE[$cookieName])) {
if (empty($_GET[$cookieName])) {
$id = uniqidV4();
$_GET[$cookieName] = $id;
}
if (empty($_SESSION[$cookieName])) {
_session_start();
$_SESSION[$cookieName] = $_GET[$cookieName];
} else {
$_GET[$cookieName] = $_SESSION[$cookieName];
}
if (!_setcookie($cookieName, $_GET[$cookieName], strtotime("+ 1 year"))) {
return "getDeviceIDError";
}
$_COOKIE[$cookieName] = $_GET[$cookieName];
return $_GET[$cookieName];
}
return $_COOKIE[$cookieName];
}
function uniqidV4() {
$randomString = openssl_random_pseudo_bytes(16);
$time_low = bin2hex(substr($randomString, 0, 4));
$time_mid = bin2hex(substr($randomString, 4, 2));
$time_hi_and_version = bin2hex(substr($randomString, 6, 2));
$clock_seq_hi_and_reserved = bin2hex(substr($randomString, 8, 2));
$node = bin2hex(substr($randomString, 10, 6));
/**
* Set the four most significant bits (bits 12 through 15) of the
* time_hi_and_version field to the 4-bit version number from
* Section 4.1.3.
* @see http://tools.ietf.org/html/rfc4122#section-4.1.3
*/
$time_hi_and_version = hexdec($time_hi_and_version);
$time_hi_and_version = $time_hi_and_version >> 4;
$time_hi_and_version = $time_hi_and_version | 0x4000;
/**
* Set the two most significant bits (bits 6 and 7) of the
* clock_seq_hi_and_reserved to zero and one, respectively.
*/
$clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved);
$clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
$clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;
return sprintf('%08s-%04s-%04x-%04x-%012s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node);
}
// guid
function _setcookie($cookieName, $value, $expires = 0) {
if (empty($expires)) {
if (empty($config) || !is_object($config)) {
$config = new Configuration();
}
$expires = time() + $config->getSession_timeout();
}
if (version_compare(phpversion(), '7.3', '>=')) {
$cookie_options = array(
'expires' => $expires,
'path' => '/',
'domain' => getDomain(),
'secure' => true,
'httponly' => false,
'samesite' => 'None');
return setcookie($cookieName, $value, $cookie_options);
} else {
return setcookie($cookieName, $value, (int) $expires, "/", getDomain());
}
}
function _unsetcookie($cookieName) {
$domain = getDomain();
$expires = strtotime("-10 years");
$value = "";
_setcookie($cookieName, $value, $expires);
setcookie($cookieName, $value, (int) $expires, "/") && setcookie($cookieName, $value, (int) $expires);
setcookie($cookieName, $value, (int) $expires, "/", str_replace("www", "", $domain));
setcookie($cookieName, $value, (int) $expires, "/", "www." . $domain);
setcookie($cookieName, $value, (int) $expires, "/", "." . $domain);
setcookie($cookieName, $value, (int) $expires, "/", $domain);
setcookie($cookieName, $value, (int) $expires, "/");
setcookie($cookieName, $value, (int) $expires);
unset($_COOKIE[$cookieName]);
}
/**
* This function is not 100% but try to tell if the site is in an iFrame
* @global type $global
* @return boolean
*/
function isIframeInDifferentDomain() {
global $global;
if (!isIframe()) {
return false;
}
return isSameDomainAsMyAVideo($_SERVER['HTTP_REFERER']);
}
function isIframe() {
global $global;
if (isset($_SERVER['HTTP_SEC_FETCH_DEST']) && $_SERVER['HTTP_SEC_FETCH_DEST'] === 'iframe') {
return true;
}
if (empty($_SERVER['HTTP_REFERER'])) {
return false;
}
return true;
}
function getCredentialsURL() {
global $global;
return "webSiteRootURL=" . urlencode($global['webSiteRootURL']) . "&user=" . urlencode(User::getUserName()) . "&pass=" . urlencode(User::getUserPass()) . "&encodedPass=1";
}
function gotToLoginAndComeBackHere($msg) {
global $global;
if (!empty($_GET['comebackhere'])) {
return false;
}
header("Location: {$global['webSiteRootURL']}user?redirectUri=" . urlencode(getSelfURI()) . "&msg=" . urlencode($msg) . "&comebackhere=1");
exit;
}
function setAlertMessage($msg, $type = "msg") {
_session_start();
$_SESSION['YPTalertMessage'][] = array($msg, $type);
}
function setToastMessage($msg) {
setAlertMessage($msg, "toast");
}
function showAlertMessage() {
if (!empty($_SESSION['YPTalertMessage'])) {
foreach ($_SESSION['YPTalertMessage'] as $value) {
if (!empty($value[0])) {
if (empty($_GET[$value[1]])) {
$_GET[$value[1]] = array();
}
$_GET[$value[1]][] = $value[0];
}
}
_session_start();
unset($_SESSION['YPTalertMessage']);
}
$joinString = array('error', 'msg', 'success');
foreach ($joinString as $value) {
if (!empty($_GET[$value]) && is_array($_GET[$value])) {
$_GET[$value] = array_unique($_GET[$value]);
$newStr = array();
foreach ($_GET[$value] as $value2) {
if (!empty($value2)) {
$newStr[] = $value2;
}
}
$_GET[$value] = implode(" ", $newStr);
}
}
$check = array('error', 'msg', 'success', 'toast');
foreach ($check as $value) {
if (!empty($_GET[$value])) {
if (is_array($_GET[$value])) {
$newStr = array();
foreach ($_GET[$value] as $key => $value2) {
$value2 = str_replace('"', "''", $value2);
if (!empty($value2)) {
$newStr[] = $value2;
}
}
$_GET[$value] = $newStr;
} else {
$_GET[$value] = str_replace('"', "''", $_GET[$value]);
}
}
}
echo "/** showAlertMessage **/", PHP_EOL;
if (!empty($_GET['error'])) {
echo 'avideoAlertError("' . $_GET['error'] . '");';
echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");';
}
if (!empty($_GET['msg'])) {
echo 'avideoAlertInfo("' . $_GET['msg'] . '");';
echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");';
}
if (!empty($_GET['success'])) {
echo 'avideoAlertSuccess("' . $_GET['success'] . '");';
echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");';
}
if (!empty($_GET['toast'])) {
if (!is_array($_GET['toast'])) {
$_GET['toast'] = array($_GET['toast']);
} else {
$_GET['toast'] = array_unique($_GET['toast']);
}
foreach ($_GET['toast'] as $key => $value) {
$hideAfter = strlen(strip_tags($value)) * 150;
if ($hideAfter < 3000) {
$hideAfter = 3000;
}
if ($hideAfter > 15000) {
$hideAfter = 15000;
}
echo '$.toast({
text: "' . $value . '",
hideAfter: ' . $hideAfter . ' // in milli seconds
});console.log("Toast Hide after ' . $hideAfter . '");';
}
echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");';
}
echo PHP_EOL, "/** showAlertMessage END **/";
}
function getResolutionLabel($res) {
if ($res == 720) {
return "" . getResolutionText($res) . " ";
} elseif ($res == 1080) {
return "" . getResolutionText($res) . " ";
} elseif ($res == 1440) {
return "" . getResolutionText($res) . " ";
} elseif ($res == 2160) {
return "" . getResolutionText($res) . " ";
} elseif ($res == 4320) {
return "" . getResolutionText($res) . " ";
} else {
return '';
}
}
function getResolutionText($res) {
if ($res == 720) {
return "HD";
} elseif ($res == 1080) {
return "FHD";
} elseif ($res == 1440) {
return "FHD+";
} elseif ($res == 2160) {
return "4K";
} elseif ($res == 4320) {
return "8K";
} else {
return '';
}
}
// just realize the readdir is a lot faster then glob
function _glob($dir, $pattern) {
global $_glob;
if (empty($dir)) {
return array();
}
if (empty($_glob)) {
$_glob = array();
}
$name = md5($dir . $pattern);
if (isset($_glob[$name])) {
return $_glob[$name];
}
$dir = rtrim($dir, '/') . '/';
$array = array();
if ($handle = opendir($dir)) {
$count = 0;
while (false !== ($file_name = readdir($handle))) {
if (preg_match($pattern, $file_name)) {
$array[] = "{$dir}{$file_name}";
}
}
closedir($handle);
}
$_glob[$name] = $array;
return $array;
}
function globVideosDir($filename, $filesOnly = false) {
global $global;
if (empty($filename)) {
return array();
}
$cleanfilename = Video::getCleanFilenameFromFile($filename);
$pattern = "/{$cleanfilename}.*";
if (!empty($filesOnly)) {
$formats = getValidFormats();
$pattern .= ".(" . implode("|", $formats) . ")";
}
$pattern .= "/";
return _glob(getVideosDir() . "", $pattern);
}
function getValidFormats() {
$video = array('webm', 'mp4', 'm3u8');
$audio = array('mp3', 'ogg');
$image = array('jpg', 'gif', 'webp');
return array_merge($video, $audio, $image);
}
function isValidFormats($format) {
$format = str_replace(".", "", $format);
return in_array($format, getValidFormats());
}
function getTimerFromDates($startTime, $endTime = 0) {
if (!is_int($startTime)) {
$startTime = strtotime($startTime);
}
if (!is_int($endTime)) {
$endTime = strtotime($endTime);
}
if (empty($endTime)) {
$endTime = time();
}
$timer = abs($endTime - $startTime);
$uid = uniqid();
return " ";
}
function getServerClock() {
$id = uniqid();
$today = getdate();
$html = '00:00:00 ';
$html .= "";
return $html;
}
/**
* Xsendfile and FFMPEG are required for this feature
* @global type $global
* @param type $filepath
* @return boolean
*/
function downloadHLS($filepath) {
global $global;
if (!CustomizeUser::canDownloadVideos()) {
_error_log("downloadHLS: CustomizeUser::canDownloadVideos said NO");
return false;
}
if (!file_exists($filepath)) {
_error_log("downloadHLS: file NOT found: {$filepath}");
return false;
}
$output = m3u8ToMP4($filepath);
if (empty($output)) {
die("downloadHLS was not possible");
}
$outputpath = $output['path'];
$outputfilename = $output['filename'];
if (!empty($_REQUEST['title'])) {
$quoted = sprintf('"%s"', addcslashes(basename($_REQUEST['title']), '"\\'));
} elseif (!empty($_REQUEST['file'])) {
$quoted = sprintf('"%s"', addcslashes(basename($_REQUEST['file']), '"\\')) . ".mp4";
} else {
$quoted = $outputfilename;
}
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=' . $quoted);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("X-Sendfile: {$outputpath}");
exit;
}
function playHLSasMP4($filepath) {
global $global;
if (!CustomizeUser::canDownloadVideos()) {
_error_log("playHLSasMP4: CustomizeUser::canDownloadVideos said NO");
return false;
}
if (!file_exists($filepath)) {
_error_log("playHLSasMP4: file NOT found: {$filepath}");
return false;
}
$output = m3u8ToMP4($filepath);
if (empty($output)) {
die("playHLSasMP4 was not possible");
}
$outputpath = $output['path'];
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Content-type: video/mp4');
header('Content-Length: ' . filesize($outputpath));
header("X-Sendfile: {$outputpath}");
exit;
}
function m3u8ToMP4($input) {
$videosDir = getVideosDir();
$outputfilename = str_replace($videosDir, "", $input);
$parts = explode("/", $outputfilename);
$resolution = Video::getResolutionFromFilename($input);
$outputfilename = $parts[0] . "_{$resolution}_.mp4";
$outputpath = "{$videosDir}cache/downloads/{$outputfilename}";
make_path($outputpath);
if (empty($outputfilename)) {
_error_log("downloadHLS: empty outputfilename {$outputfilename}");
return false;
}
$filepath = escapeshellcmd($input);
$outputpath = escapeshellcmd($outputpath);
if (!file_exists($outputpath)) {
$command = get_ffmpeg() . " -allowed_extensions ALL -y -i {$filepath} -c:v copy -c:a copy -bsf:a aac_adtstoasc -strict -2 {$outputpath}";
//var_dump($outputfilename, $command, $_GET, $filepath, $quoted);exit;
exec($command . " 2>&1", $output, $return);
if (!empty($return)) {
_error_log("downloadHLS: ERROR 1 " . implode(PHP_EOL, $output));
$command = get_ffmpeg() . " -y -i {$filepath} -c:v copy -c:a copy -bsf:a aac_adtstoasc -strict -2 {$outputpath}";
//var_dump($outputfilename, $command, $_GET, $filepath, $quoted);exit;
exec($command . " 2>&1", $output, $return);
if (!empty($return)) {
_error_log("downloadHLS: ERROR 2 " . implode(PHP_EOL, $output));
return false;
}
}
}
return array('path' => $outputpath, 'filename' => $outputfilename);
}
function getSocialModal($videos_id, $url = "", $title = "") {
global $global;
$video['id'] = $videos_id;
$sharingUid = uniqid();
ob_start();
?>
$contents, 'id' => $sharingUid);
}
function getCroppie(
$buttonTitle,
$callBackJSFunction,
$resultWidth,
$resultHeight,
$viewportWidth = 0,
$boundary = 25,
$viewportHeight = 0
) {
global $global;
if (empty($viewportWidth)) {
$viewportWidth = $resultWidth;
}
$zoom = 0;
if (empty($viewportHeight)) {
$zoom = ($viewportWidth / $resultWidth);
$viewportHeight = $zoom * $resultHeight;
}
$boundaryWidth = $viewportWidth + $boundary;
$boundaryHeight = $viewportHeight + $boundary;
$uid = uniqid();
ob_start();
include $global['systemRootPath'] . 'objects/functionCroppie.php';
$contents = ob_get_contents();
ob_end_clean();
$callBackJSFunction = addcslashes($callBackJSFunction, "'");
return array(
"html" => $contents,
"id" => "croppie{$uid}",
"uploadCropObject" => "uploadCrop{$uid}",
"getCroppieFunction" => "getCroppie(uploadCrop{$uid}, '{$callBackJSFunction}', {$resultWidth}, {$resultHeight});",
"createCroppie" => "createCroppie{$uid}",
"restartCroppie" => "restartCroppie{$uid}"
);
}
function saveCroppieImage($destination, $postIndex = "imgBase64") {
if (empty($_POST[$postIndex])) {
return false;
}
$fileData = base64DataToImage($_POST[$postIndex]);
return file_put_contents($destination, $fileData);
}
function get_ffmpeg($ignoreGPU = false) {
global $global;
//return 'ffmpeg -user_agent "'.getSelfUserAgent("FFMPEG").'" ';
//return 'ffmpeg -headers "User-Agent: '.getSelfUserAgent("FFMPEG").'" ';
$ffmpeg = 'ffmpeg ';
if (empty($ignoreGPU) && !empty($global['ffmpegGPU'])) {
$ffmpeg .= ' --enable-nvenc ';
}
if (!empty($global['ffmpeg'])) {
$ffmpeg = "{$global['ffmpeg']}{$ffmpeg}";
}
return $ffmpeg;
}
function isHTMLPage($url) {
if ($type = getHeaderContentTypeFromURL($url)) {
if (preg_match('/text\/html/i', $type)) {
return true;
}
}
return false;
}
function getHeaderContentTypeFromURL($url) {
if (isValidURL($url) && $type = get_headers($url, 1)["Content-Type"]) {
return $type;
}
return false;
}
function canFullScreen() {
global $doNotFullScreen;
if (!empty($doNotFullScreen) || isSerie() || !isVideo()) {
return false;
}
return true;
}
function getTinyMCE($id) {
global $global;
ob_start();
include $global['systemRootPath'] . 'objects/functionsGetTinyMCE.php';
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
function pathToRemoteURL($filename) {
global $pathToRemoteURL, $global;
if (!isset($pathToRemoteURL)) {
$pathToRemoteURL = array();
}
if (isset($pathToRemoteURL[$filename])) {
return $pathToRemoteURL[$filename];
}
$url = $filename;
if (!file_exists($filename) || filesize($filename) < 1000) {
$fileName = getFilenameFromPath($filename);
if ($yptStorage = AVideoPlugin::loadPluginIfEnabled("YPTStorage")) {
$source = $yptStorage->getAddress("{$fileName}");
$url = $source['url'];
} else
if ($aws_s3 = AVideoPlugin::loadPluginIfEnabled("AWS_S3")) {
$source = $aws_s3->getAddress("{$fileName}");
$url = $source['url'];
} else
if ($bb_b2 = AVideoPlugin::loadPluginIfEnabled("Blackblaze_B2")) {
$source = $bb_b2->getAddress("{$fileName}");
$url = $source['url'];
} else
if ($ftp = AVideoPlugin::loadPluginIfEnabled("FTP_Storage")) {
$source = $ftp->getAddress("{$fileName}");
$url = $source['url'];
}
}
if (empty($url)) {
$url = $filename;
}
//$url = str_replace(array($global['systemRootPath'], '/videos/videos/'), array("", '/videos/'), $url);
$pathToRemoteURL[$filename] = $url;
return $url;
}
function getFilenameFromPath($path) {
global $global;
$fileName = str_replace(getVideosDir() . "", "", $path);
$fileName = Video::getCleanFilenameFromFile($fileName);
return $fileName;
}
function showCloseButton() {
global $global, $showCloseButtonIncluded;
if (!empty($showCloseButtonIncluded)) {
return false;
}
if (isSerie()) {
return false;
}
if (!isLive() && $obj = AVideoPlugin::getDataObjectIfEnabled("Gallery")) {
if (!empty($obj->playVideoOnFullscreen)) {
$_REQUEST['showCloseButton'] = 1;
}
}
if (isLive() && $obj = AVideoPlugin::getDataObjectIfEnabled("Live")) {
if (!empty($obj->playLiveInFullScreen)) {
$_REQUEST['showCloseButton'] = 1;
}
}
if (!empty($_REQUEST['showCloseButton'])) {
$showCloseButtonIncluded = 1;
include $global['systemRootPath'] . 'view/include/youtubeModeOnFullscreenCloseButton.php';
return true;
}
return false;
}
function getThemes() {
global $_getThemes, $global;
if (isset($_getThemes)) {
return $_getThemes;
}
$_getThemes = array();
foreach (glob("{$global['systemRootPath']}view/css/custom/*.css") as $filename) {
$fileEx = basename($filename, ".css");
$_getThemes[] = $fileEx;
}
return $_getThemes;
}
function getCurrentTheme() {
global $config;
if (!empty($_COOKIE['customCSS'])) {
return $_COOKIE['customCSS'];
}
return $config->getTheme();
}
/*
* $users_id="" or 0 means send messages to all users
* $users_id="-1" means send to no one
*/
function sendSocketMessage($msg, $callbackJSFunction = "", $users_id = "-1", $send_to_uri_pattern = "") {
if (AVideoPlugin::isEnabledByName('Socket')) {
if (!is_string($msg)) {
$msg = json_encode($msg);
}
$obj = Socket::send($msg, $callbackJSFunction, $users_id, $send_to_uri_pattern);
if ($obj->error) {
_error_log("sendSocketMessage " . $obj->msg, AVideoLog::$ERROR);
}
return $obj;
}
return false;
}
function sendSocketMessageToUsers_id($msg, $users_id, $callbackJSFunction = "") {
if (!is_array($users_id)) {
$users_id = array($users_id);
}
$resp = array();
foreach ($users_id as $value) {
$resp[] = sendSocketMessage($msg, $callbackJSFunction, $value);
}
return $resp;
}
function sendSocketMessageToAll($msg, $callbackJSFunction = "", $send_to_uri_pattern = "") {
return sendSocketMessage($msg, $callbackJSFunction, "", $send_to_uri_pattern);
}
function sendSocketMessageToNone($msg, $callbackJSFunction = "") {
return sendSocketMessage($msg, $callbackJSFunction, -1);
}
function execAsync($command) {
$command = escapeshellarg($command);
// If windows, else
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
//echo $command;
//$pid = system("start /min ".$command. " > NUL");
$commandString = "start /B " . $command;
pclose($pid = popen($commandString, "r"));
var_dump($pid, $commandString);
} else {
$pid = exec($command . " > /dev/null 2>&1 & echo $!; ");
}
return $pid;
}
function killProcess($pid) {
$pid = intval($pid);
if (empty($pid)) {
return false;
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
exec("taskkill /F /PID $pid");
} else {
exec("kill -9 $pid");
}
return true;
}
function getPIDUsingPort($port) {
$port = intval($port);
if (empty($port)) {
return false;
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$command = 'netstat -ano | findstr ' . $port;
exec($command, $output, $retval);
$pid = 0;
foreach ($output as $value) {
if (preg_match('/LISTENING[^0-9]+([0-9]+)/i', $value, $matches)) {
if (!empty($matches[1])) {
$pid = intval($matches[1]);
return $pid;
}
}
}
} else {
$command = 'lsof -n -i :' . $port . ' | grep LISTEN';
exec($command, $output, $retval);
$pid = 0;
foreach ($output as $value) {
if (preg_match('/[^ ] +([0-9]+).*/i', $value, $matches)) {
if (!empty($matches[1])) {
$pid = intval($matches[1]);
return $pid;
}
}
}
}
return false;
}
function isURL200($url) {
//error_log("isURL200 checking URL {$url}");
$headers = @get_headers($url);
if(!is_array($headers)){
$headers = array($headers);
}
foreach ($headers as $value) {
if (
strpos($headers[0], '200') ||
strpos($headers[0], '302') ||
strpos($headers[0], '304')
) {
return true;
}
}
return false;
}
function getStatsNotifications() {
$json = Live::getStats();
if (!is_array($json) && is_object($json)) {
$json = object_to_array($json);
}
$appArray = AVideoPlugin::getLiveApplicationArray();
if (!empty($appArray)) {
if (empty($json)) {
$json = new stdClass();
}
$json['error'] = false;
if (empty($json['msg'])) {
$json['msg'] = "OFFLINE";
}
$json['nclients'] = count($appArray);
if (empty($json['applications'])) {
$json['applications'] = array();
}
$json['applications'] = array_merge($json['applications'], $appArray);
}
$count = 0;
if (!isset($json['total'])) {
$json['total'] = 0;
}
if (!empty($json['applications'])) {
$json['total'] += count($json['applications']);
}
while (!empty($json[$count])) {
$json['total'] += count($json[$count]->applications);
$count++;
}
if (empty($json['countLiveStream']) || $json['countLiveStream'] < $json['total']) {
$json['countLiveStream'] = $json['total'];
}
return $json;
}
function getSocketConnectionLabel() {
$html = '
' . __('Disconnected') . '
' . __('Connected') . '
';
return $html;
}
function getSocketVideoClassName($videos_id){
return 'total_on_videos_id_'.$videos_id;
}
function getSocketLiveClassName($key, $live_servers_id){
return 'total_on_live_'.$key.'_'.intval($live_servers_id);
}
function getSocketLiveLinksClassName($live_links_id){
return 'total_on_live_links_id_'.$live_links_id;
}
function getLiveUsersLabelVideo($videos_id, $totalViews = null, $viewsClass = "label label-default", $counterClass = "label label-primary"){
if(AVideoPlugin::isEnabledByName('LiveUsers') && method_exists("LiveUsers", "getLabels")){
return LiveUsers::getLabels(getSocketVideoClassName($videos_id), $totalViews, $viewsClass, $counterClass);
}
}
function getLiveUsersLabelLive($key, $live_servers_id, $viewsClass = "label label-default", $counterClass = "label label-primary"){
if(AVideoPlugin::isEnabledByName('LiveUsers') && method_exists("LiveUsers", "getLabels")){
$totalViews = LiveUsers::getTotalUsers($key, $live_servers_id);
return LiveUsers::getLabels(getSocketLiveClassName($key, $live_servers_id), $totalViews, $viewsClass, $counterClass);
}
}
function getLiveUsersLabelLiveLinks($liveLinks_id, $totalViews = null, $viewsClass = "label label-default", $counterClass = "label label-primary"){
if(AVideoPlugin::isEnabledByName('LiveUsers') && method_exists("LiveUsers", "getLabels")){
return LiveUsers::getLabels(getSocketLiveLinksClassName($liveLinks_id), $totalViews, $viewsClass, $counterClass);
}
}
function getLiveUsersLabel($viewsClass = "label label-default", $counterClass = "label label-primary"){
if(AVideoPlugin::isEnabledByName('LiveUsers')){
$live = isLive();
if(!empty($live)){
if(!empty($live['key'])){
return getLiveUsersLabelLive($live['key'], $live['live_servers_id'], $viewsClass, $counterClass);
}else if(!empty($live['liveLinks_id'])){
return getLiveUsersLabelLiveLinks($live['liveLinks_id'], null, $viewsClass, $counterClass);
}
}else{
$videos_id = getVideos_id();
if(!empty($videos_id)){
$v = new Video("", "", $videos_id);
$totalViews = $v->getViews_count();
return getLiveUsersLabelVideo($videos_id, $totalViews, $viewsClass, $counterClass);
}
}
}
return "";
}
function getHTMLTitle($titleArray){
global $config, $global;
if(!is_array($titleArray)){
$titleArray = array();
}
$titleArray[] = $config->getWebSiteTitle();
$title = implode($config->getPageTitleSeparator(), $titleArray);
$global['pageTitle'] = $title;
return "{$title} ";
}
+function getButtonSignInAndUp(){
+ $signIn = getButtonSignIn();
+ $signUp = getButtonSignUp();
+ $html = $signIn.$signUp;
+ if(!empty($signIn) && !empty($signIn)){
+ return ''.$html.'
';
+ }else{
+ return $html;
+ }
+}
+
+function getButtonSignUp(){
+ global $global;
+ $obj = AVideoPlugin::getDataObject('CustomizeUser');
+ if(!empty($obj->disableNativeSignUp)){
+ return '';
+ }
+
+ $url = $global['webSiteRootURL'].'signUp';
+ $url = addQueryStringParameter($url, 'redirectUri', getRedirectUri());
+
+ $html = ' '.__("Sign Up").' ';
+ return $html;
+}
+function getButtonSignIn(){
+ global $global;
+ $obj = AVideoPlugin::getDataObject('CustomizeUser');
+ if(!empty($obj->disableNativeSignIn)){
+ return '';
+ }
+
+ $url = $global['webSiteRootURL'].'user';
+ $url = addQueryStringParameter($url, 'redirectUri', getRedirectUri());
+
+ $html = ' '.__("Sign In").' ';
+ return $html;
+}
+
function getTitle(){
global $global;
if(empty($global['pageTitle'])){
$url = getSelfURI();
$global['pageTitle'] = str_replace($global['webSiteRootURL'], '', $url);
if(preg_match('/\/plugin\/([^\/])/i', $url, $matches)){
$global['pageTitle'] = __('Plugin').' '.__($matches[1]);
}
$title = $global['pageTitle'];
}
return $global['pageTitle'];
}
\ No newline at end of file
diff --git a/plugin/Live/Live.php b/plugin/Live/Live.php
index 6e192e59a..7f417db9f 100644
--- a/plugin/Live/Live.php
+++ b/plugin/Live/Live.php
@@ -1,1496 +1,1506 @@
and receive HLS streaming from servers";
$lu = AVideoPlugin::loadPlugin("LiveUsers");
if (!empty($lu)) {
if (version_compare($lu->getPluginVersion(), "2.0") < 0) {
$desc .= "You MUST update your LiveUsers plugin to version 2.0 or greater
";
}
}
return $desc;
}
public function getName() {
return "Live";
}
public function getHTMLMenuRight() {
global $global;
$buttonTitle = $this->getButtonTitle();
$obj = $this->getDataObject();
if (!empty($obj->hideTopButton)) {
return '';
}
include $global['systemRootPath'] . 'plugin/Live/view/menuRight.php';
}
public function getUUID() {
return "e06b161c-cbd0-4c1d-a484-71018efa2f35";
}
public function getPluginVersion() {
return "5.3";
}
public function updateScript() {
global $global;
//update version 2.0
$sql = "SELECT 1 FROM live_transmitions_history LIMIT 1";
$res = sqlDAL::readSql($sql);
$fetch = sqlDAL::fetchAssoc($res);
if (!$fetch) {
sqlDal::writeSql(file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV2.0.sql'));
}
//update version 3.0
$sql = "SELECT 1 FROM live_transmition_history_log LIMIT 1";
$res = sqlDAL::readSql($sql);
$fetch = sqlDAL::fetchAssoc($res);
if (!$fetch) {
sqlDal::writeSql(file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV3.0.sql'));
}
//update version 4.0
$sql = "SELECT 1 FROM live_servers LIMIT 1";
$res = sqlDAL::readSql($sql);
$fetch = sqlDAL::fetchAssoc($res);
if (!$fetch) {
$sqls = file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV4.0.sql');
$sqlParts = explode(";", $sqls);
foreach ($sqlParts as $value) {
sqlDal::writeSql(trim($value));
}
}
//update version 5.0
$sql = "SELECT 1 FROM live_restreams LIMIT 1";
$res = sqlDAL::readSql($sql);
$fetch = sqlDAL::fetchAssoc($res);
if (!$fetch) {
$sqls = file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV5.0.sql');
$sqlParts = explode(";", $sqls);
foreach ($sqlParts as $value) {
sqlDal::writeSql(trim($value));
}
}
//update version 5.1
if (AVideoPlugin::compareVersion($this->getName(), "5.1") < 0) {
$sqls = file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV5.1.sql');
$sqlParts = explode(";", $sqls);
foreach ($sqlParts as $value) {
sqlDal::writeSql(trim($value));
}
}
//update version 5.2
if (AVideoPlugin::compareVersion($this->getName(), "5.2") < 0) {
$sqls = file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV5.2.sql');
$sqlParts = explode(";", $sqls);
foreach ($sqlParts as $value) {
sqlDal::writeSql(trim($value));
}
}
//update version 5.2
if (AVideoPlugin::compareVersion($this->getName(), "6.0") < 0) {
$sqls = file_get_contents($global['systemRootPath'] . 'plugin/Live/install/updateV6.0.sql');
$sqlParts = explode(";", $sqls);
foreach ($sqlParts as $value) {
sqlDal::writeSql(trim($value));
}
}
return true;
}
public function getEmptyDataObject() {
global $global;
$server = parse_url($global['webSiteRootURL']);
$scheme = "http";
$port = "8080";
if (strtolower($server["scheme"]) == "https") {
$scheme = "https";
$port = "8443";
}
$obj = new stdClass();
$obj->button_title = "LIVE";
self::addDataObjectHelper('button_title', 'Button Title', 'This is the title that will appear in your button to enter in the Live panel');
$obj->server = "rtmp://{$server['host']}/live";
self::addDataObjectHelper('server', 'RTMP Server URL', 'Usually it is ' . "rtmp://{$server['host']}/live");
$obj->playerServer = "{$scheme}://{$server['host']}:{$port}/live";
self::addDataObjectHelper('playerServer', 'Player URL', 'This is a URL to your NGINX server, this URL will be used by the HTML5 player, If your site is HTTPS your player URL MUST be HTTPS as well, usually it is ' . "{$scheme}://{$server['host']}:{$port}/live");
$obj->stats = "{$scheme}://{$server['host']}:{$port}/stat";
self::addDataObjectHelper('stats', 'Stats Page URL', 'When you installed the NGINX you also install the stat.xsl, we will use it to grab the information when you have livestreams running, usually it is ' . "{$scheme}://{$server['host']}:{$port}/stat");
$obj->restreamerURL = "{$global['webSiteRootURL']}plugin/Live/standAloneFiles/restreamer.json.php";
self::addDataObjectHelper('restreamerURL', 'Restreamer URL', 'https://github.com/WWBN/AVideo/wiki/Restream');
$obj->controlURL = "{$global['webSiteRootURL']}plugin/Live/standAloneFiles/control.json.php";
self::addDataObjectHelper('controlURL', 'Control URL', 'Still under development');
$obj->disableRestream = false;
self::addDataObjectHelper('disableRestream', 'Disable Restream', 'If you check this, we will not send requests to your Restreamer URL');
$obj->disableDVR = false;
self::addDataObjectHelper('disableDVR', 'Disable DVR', 'Enable or disable the DVR Feature, you can control the DVR length in your nginx.conf on the parameter hls_playlist_length');
$obj->disableGifThumbs = false;
self::addDataObjectHelper('disableGifThumbs', 'Disable Gif Thumbs', 'This option will disable the Animated Gif render, it will save some hardware capacity from your encoder and may speedup your page');
$obj->disableLiveThumbs = false;
self::addDataObjectHelper('disableLiveThumbs', 'Disable Live thumbnails', 'This option will disable the çive image extraction and will use the user static image, it will save some hardware capacity from your encoder and may speedup your page');
$obj->hideTopButton = false;
self::addDataObjectHelper('hideTopButton', 'Hide Top Button', 'This will hide the "Go Live" button on the top menu bar');
$obj->useAadaptiveMode = false;
self::addDataObjectHelper('useAadaptiveMode', 'Adaptive mode', 'https://github.com/WWBN/AVideo/wiki/Adaptive-Bitrates-on-Livestream');
$obj->protectLive = false;
self::addDataObjectHelper('protectLive', 'Live Protection', 'With this your encryption key will be protected, and only your site player will be able to play your videos, download tools will not be able to download your video. if you want to share your live externally you can use the embed and you will still be protected. but if you want to use the m3u8 file you must disable this');
$obj->experimentalWebcam = false;
self::addDataObjectHelper('experimentalWebcam', 'Experimental Webcam', 'Requires flash and it is deprecated, will be removed. not recommend to enable it.');
$obj->doNotShowLiveOnVideosList = false;
self::addDataObjectHelper('doNotShowLiveOnVideosList', 'Do not show live on videos list', 'We will not show the live thumbs on the main Gallery page');
$obj->doNotShowLiveOnCategoryList = false;
self::addDataObjectHelper('doNotShowLiveOnCategoryList', 'Do not show live on site category list', 'We will not show the live thumbs on the main Gallery page');
$obj->doNotShowOfflineLiveOnCategoryList = false;
self::addDataObjectHelper('doNotShowOfflineLiveOnCategoryList', 'Do not show offline lives on site category list', 'We will not show the live thumbs on the main Gallery page if it is offline');
$obj->limitLiveOnVideosList = 12;
self::addDataObjectHelper('limitLiveOnVideosList', 'Videos List Limit', 'This will limit the maximum of videos that you will see in the Videos page');
//$obj->doNotShowGoLiveButton = false;
//self::addDataObjectHelper('doNotShowGoLiveButton', 'Hide Top Button', 'This will hide the "Go Live" button on the top menu bar');
$obj->doNotProcessNotifications = false;
self::addDataObjectHelper('doNotProcessNotifications', 'Do not show notifications', 'Do not show the notification on the top bar');
$obj->useLiveServers = false;
self::addDataObjectHelper('useLiveServers', 'Use Live Servers', 'Check this if you will use External Live Servers https://github.com/WWBN/AVideo/wiki/Live-Plugin#livestream-server-balance ');
$obj->disableMeetCamera = false;
self::addDataObjectHelper('disableMeetCamera', 'Disable Meet camera', 'This requires out Meet Server, with the Meet camera you can use your PC webcam directly in the webpage or mobile to make livestreams');
$obj->playLiveInFullScreen = false;
self::addDataObjectHelper('playLiveInFullScreen', 'Play Livestream in Full Screen');
$obj->playLiveInFullScreenOnIframe = false;
self::addDataObjectHelper('playLiveInFullScreenOnIframe', 'Play Livestream in Full Screen on IFrame');
$obj->hls_path = "/HLS/live";
self::addDataObjectHelper('hls_path', 'HLS Path URL', 'Used only when we stop a Live, we use this path to delete the files');
$obj->requestStatsTimout = 4; // if the server does not respond we stop wait
self::addDataObjectHelper('requestStatsTimout', 'Stats Timout', 'If a remote server (stats page) does not respond we stop waiting after this timeout');
$obj->cacheStatsTimout = 15; // we will cache the result
self::addDataObjectHelper('cacheStatsTimout', 'Stats Cache Timeout', 'we will cache the result, this will save some resources');
$obj->requestStatsInterval = 15; // how many seconds untill request the stats again
self::addDataObjectHelper('requestStatsInterval', 'Stats Request Interval', 'how many seconds until request the stats again');
$obj->streamDeniedMsg = "You can not stream live videos";
self::addDataObjectHelper('streamDeniedMsg', 'Denied Message', 'We will show this message when a user is not allowed so watch a livestream');
return $obj;
}
public function getHeadCode() {
global $global;
$obj = $this->getDataObject();
// preload image
$js = "";
$css = '';
if (!empty($obj->playLiveInFullScreen)) {
if ((isLive() || isEmbed()) && canFullScreen()) {
$css .= ' ';
$css .= '';
}
$js .= '';
$css .= '';
}
return $js . $css;
}
public function getFooterCode() {
$obj = $this->getDataObject();
global $global;
$js = '';
if (!empty($obj->playLiveInFullScreen)) {
$js = '';
$js .= '';
}else
if (!empty($obj->playLiveInFullScreenOnIframe)) {
$js = '';
$js .= '';
}
include $global['systemRootPath'].'plugin/Live/view/footer.php';
return $js;
}
public function getButtonTitle() {
$o = $this->getDataObject();
return $o->button_title;
}
public function getKey() {
$o = $this->getDataObject();
return $o->key;
}
static function getDestinationApplicationName() {
$server = self::getPlayerServer();
$server = rtrim($server, "/");
$parts = explode("/", $server);
$app = array_pop($parts);
$domain = self::getControl();
//return "{$domain}/control/drop/publisher?app={$app}&name={$key}";
return "{$app}?p=" . User::getUserPass();
}
static function getDestinationHost() {
$server = self::getServer();
$host = parse_url($server, PHP_URL_HOST);
return $host;
}
static function getDestinationPort() {
$server = self::getServer();
$port = parse_url($server, PHP_URL_PORT);
if (empty($port)) {
$port = 1935;
}
return $port;
}
static function getServer($live_servers_id = -1) {
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj->useLiveServers)) {
if ($live_servers_id < 0) {
$live_servers_id = self::getCurrentLiveServersId();
}
$ls = new Live_servers($live_servers_id);
if (!empty($ls->getRtmp_server())) {
return $ls->getRtmp_server();
}
}
return $obj->server;
}
static function getDropURL($key) {
$server = self::getPlayerServer();
$server = rtrim($server, "/");
$parts = explode("/", $server);
$app = array_pop($parts);
$domain = self::getControl();
//return "{$domain}/control/drop/publisher?app={$app}&name={$key}";
return "{$domain}?command=drop_publisher&app={$app}&name={$key}&token=" . getToken(60);
}
static function getIsRecording($key) {
$server = self::getPlayerServer();
$server = rtrim($server, "/");
$parts = explode("/", $server);
$app = array_pop($parts);
$domain = self::getControl();
//return "{$domain}/control/drop/publisher?app={$app}&name={$key}";
return "{$domain}?command=is_recording&app={$app}&name={$key}&token=" . getToken(60);
}
static function getStartRecordURL($key) {
$server = self::getPlayerServer();
$server = rtrim($server, "/");
$parts = explode("/", $server);
$app = array_pop($parts);
$domain = self::getControl();
//return "{$domain}/control/drop/publisher?app={$app}&name={$key}";
return "{$domain}?command=record_start&app={$app}&name={$key}&token=" . getToken(60);
}
static function getStopRecordURL($key) {
$server = self::getPlayerServer();
$server = rtrim($server, "/");
$parts = explode("/", $server);
$app = array_pop($parts);
$domain = self::getControl();
return "{$domain}?command=record_stop&app={$app}&name={$key}&token=" . getToken(60);
}
static function getButton($command, $live_transmition_id, $live_servers_id = 0, $iconsOnly = false, $label = "", $class = "", $tooltip = "") {
if (!User::canStream()) {
return "";
}
global $global;
$id = "getButton" . uniqid();
if (empty($live_servers_id)) {
$live_servers_id = self::getLiveServersIdRequest();
}
switch ($command) {
case "record_start":
$buttonClass = "btn btn-default btn-sm";
$iconClass = "fas fa-video";
if (empty($label)) {
$label = __("Start Record");
}
if (empty($tooltip)) {
$tooltip = __("Start Record");
}
break;
case "record_stop":
$buttonClass = "btn btn-default btn-sm";
$iconClass = "fas fa-video-slash";
if (empty($label)) {
$label = __("Stop Record");
}
if (empty($tooltip)) {
$tooltip = __("Stop Record");
}
break;
case "drop_publisher":
$buttonClass = "btn btn-default btn-sm";
$iconClass = "fas fa-wifi";
if (empty($label)) {
$label = __("Disconnect Livestream");
}
if (empty($tooltip)) {
$tooltip = __("Disconnect Livestream");
}
break;
case "drop_publisher_reset_key":
$buttonClass = "btn btn-default btn-sm";
$iconClass = "fas fa-key";
if (empty($label)) {
$label = __("Disconnect Livestream");
}
if (empty($tooltip)) {
$tooltip = __("Disconnect Livestream") . __(" and also reset the stream name/key");
}
break;
default:
return '';
}
if ($iconsOnly) {
$label = "";
}
$html = " {$label}";
$html .= "";
$html .= " ";
return $html;
}
static function getRecordControlls($live_transmition_id, $live_servers_id = 0, $iconsOnly = false) {
if (!User::canStream()) {
return "";
}
$btn = "";
$btn .= self::getButton("record_start", $live_transmition_id, $live_servers_id, $iconsOnly);
$btn .= self::getButton("record_stop", $live_transmition_id, $live_servers_id, $iconsOnly);
$btn .= "
";
return $btn;
}
static function getAllControlls($live_transmition_id, $live_servers_id = 0, $iconsOnly = false) {
if (!User::canStream()) {
return "";
}
$btn = "";
//$btn .= self::getButton("drop_publisher", $live_transmition_id, $live_servers_id);
$btn .= self::getButton("drop_publisher_reset_key", $live_transmition_id, $live_servers_id, $iconsOnly);
$btn .= self::getButton("record_start", $live_transmition_id, $live_servers_id, $iconsOnly);
$btn .= self::getButton("record_stop", $live_transmition_id, $live_servers_id, $iconsOnly);
$btn .= "
";
return $btn;
}
static function getRestreamer($live_servers_id = -1) {
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj->useLiveServers)) {
if ($live_servers_id < 0) {
$live_servers_id = self::getCurrentLiveServersId();
}
$ls = new Live_servers($live_servers_id);
if (!empty($ls->getRestreamerURL())) {
return $ls->getRestreamerURL();
}
}
return $obj->restreamerURL;
}
static function getControl($live_servers_id = -1) {
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj->controlURL)) {
if ($live_servers_id < 0) {
$live_servers_id = self::getCurrentLiveServersId();
}
$ls = new Live_servers($live_servers_id);
if (!empty($ls->getControlURL())) {
return $ls->getControlURL();
}
}
return $obj->controlURL;
}
static function getRTMPLink($users_id) {
if (!User::isLogged() || ($users_id !== User::getId() && !User::isAdmin())) {
return false;
}
$user = new User($users_id);
$trasnmition = LiveTransmition::createTransmitionIfNeed($users_id);
return self::getServer() . "?p=" . $user->getPassword() . "/" . $trasnmition['key'];
}
static function getPlayerServer() {
$obj = AVideoPlugin::getObjectData("Live");
$url = $obj->playerServer;
if (!empty($obj->useLiveServers)) {
$ls = new Live_servers(self::getCurrentLiveServersId());
if (!empty($ls->getPlayerServer())) {
$url = $ls->getPlayerServer();
}
}
$url = str_replace("encoder.gdrive.local", "192.168.1.18", $url);
return $url;
}
static function getUseAadaptiveMode() {
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj->useLiveServers)) {
$ls = new Live_servers(self::getCurrentLiveServersId());
return $ls->getUseAadaptiveMode();
}
return $obj->useAadaptiveMode;
}
static function getRemoteFile() {
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj->useLiveServers)) {
$ls = new Live_servers(self::getCurrentLiveServersId());
return $ls->getGetRemoteFile();
}
return false;
}
static function getRemoteFileFromRTMPHost($rtmpHostURI) {
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj->useLiveServers)) {
$live_servers_id = Live_servers::getServerIdFromRTMPHost($rtmpHostURI);
if ($live_servers_id) {
$ls = new Live_servers($live_servers_id);
return $ls->getGetRemoteFile();
}
}
return false;
}
static function getLiveServersIdRequest() {
if (empty($_REQUEST['live_servers_id'])) {
return 0;
}
return intval($_REQUEST['live_servers_id']);
}
static function getM3U8File($uuid, $doNotProtect = false) {
global $global;
$o = AVideoPlugin::getObjectData("Live");
$playerServer = self::getPlayerServer();
$live_servers_id = self::getLiveServersIdRequest();
$liveServer = new Live_servers($live_servers_id);
if ($liveServer->getStats_url()) {
$o->protectLive = $liveServer->getProtectLive();
$o->useAadaptiveMode = $liveServer->getUseAadaptiveMode();
}
$uuid = LiveTransmition::keyNameFix($uuid);
if ($o->protectLive && empty($doNotProtect)) {
return "{$global['webSiteRootURL']}plugin/Live/m3u8.php?live_servers_id={$live_servers_id}&uuid=" . encryptString($uuid);
} else if ($o->useAadaptiveMode) {
return $playerServer . "/{$uuid}.m3u8";
} else {
return $playerServer . "/{$uuid}/index.m3u8";
}
}
public function getDisableGifThumbs() {
$o = $this->getDataObject();
return $o->disableGifThumbs;
}
public function getStatsURL($live_servers_id = 0) {
global $global;
$o = $this->getDataObject();
if (!empty($live_servers_id)) {
$liveServer = new Live_servers($live_servers_id);
if ($liveServer->getStats_url()) {
return $liveServer->getStats_url();
}
}
return $o->stats;
}
public function getChat($uuid) {
global $global;
//check if LiveChat Plugin is available
$filename = $global['systemRootPath'] . 'plugin/LiveChat/LiveChat.php';
if (file_exists($filename)) {
require_once $filename;
LiveChat::includeChatPanel($uuid);
}
}
function getStatsObject($live_servers_id = 0) {
if (!function_exists('simplexml_load_file')) {
_error_log("Live::getStatsObject: You need to install the simplexml_load_file function to be able to see the Live stats", AVideoLog::$ERROR);
return false;
}
global $getStatsObject;
if (!empty($getStatsObject[$live_servers_id])) {
return $getStatsObject[$live_servers_id];
}
$o = $this->getDataObject();
if ($o->doNotProcessNotifications) {
$xml = new stdClass();
$xml->server = new stdClass();
$xml->server->application = array();
return $xml;
}
if (empty($o->requestStatsTimout)) {
$o->requestStatsTimout = 2;
}
ini_set('allow_url_fopen ', 'ON');
$url = $this->getStatsURL($live_servers_id);
if (!empty($_SESSION['getStatsObjectRequestStatsTimout'][$url])) {
_error_log("Live::getStatsObject RTMP Server ($url) is NOT responding we will wait less from now on => live_servers_id = ($live_servers_id) ");
// if the server already fail, do not wait mutch for it next time, just wait 0.5 seconds
$o->requestStatsTimout = $_SESSION['getStatsObjectRequestStatsTimout'][$url];
}
$data = $this->get_data($url, $o->requestStatsTimout);
if (empty($data)) {
_session_start();
if (empty($_SESSION['getStatsObjectRequestStatsTimout'])) {
$_SESSION['getStatsObjectRequestStatsTimout'] = array();
}
$_SESSION['getStatsObjectRequestStatsTimout'][$url] = $o->requestStatsTimout-1;
if($_SESSION['getStatsObjectRequestStatsTimout'][$url]<1){
$_SESSION['getStatsObjectRequestStatsTimout'][$url] = 2;
}
_error_log("Live::getStatsObject RTMP Server ($url) is OFFLINE, timeout=({$o->requestStatsTimout}) we could not connect on it => live_servers_id = ($live_servers_id) ", AVideoLog::$ERROR);
$data = 'The RTMP Server is Unavailable 0 ';
} else {
if (!empty($_SESSION['getStatsObjectRequestStatsTimout'][$url])) {
_error_log("Live::getStatsObject RTMP Server ($url) is respond again => live_servers_id = ($live_servers_id) ");
// the server respont again, wait the default time
_session_start();
$_SESSION['getStatsObjectRequestStatsTimout'][$url] = 0;
unset($_SESSION['getStatsObjectRequestStatsTimout'][$url]);
}
}
$xml = simplexml_load_string($data);
$getStatsObject[$live_servers_id] = $xml;
return $xml;
}
function get_data($url, $timeout) {
try {
$content = url_get_contents($url, "", $timeout);
return $content;
} catch (Exception $exc) {
_error_log($exc->getTraceAsString());
}
return false;
}
public function getChartTabs() {
return ' ' . __('Live videos') . ' ';
}
public function getChartContent() {
global $global;
include $global['systemRootPath'] . 'plugin/Live/report.php';
}
static public function saveHistoryLog($key) {
// get the latest history for this key
$latest = LiveTransmitionHistory::getLatest($key);
if (!empty($latest)) {
LiveTransmitionHistoryLog::addLog($latest['id']);
}
}
public function dataSetup() {
$obj = $this->getDataObject();
if (!isLive() || $obj->disableDVR) {
return "";
}
return "liveui: true";
}
static function stopLive($users_id) {
if (!User::isAdmin() && User::getId() != $users_id) {
return false;
}
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj)) {
$server = str_replace("stats", "", $obj->stats);
$lt = new LiveTransmition(0);
$lt->loadByUser($users_id);
$key = $lt->getKey();
$appName = self::getApplicationName();
$url = "{$server}control/drop/publisher?app={$appName}&name=$key";
url_get_contents($url);
$dir = $obj->hls_path . "/$key";
if (is_dir($dir)) {
exec("rm -fR $dir");
rrmdir($dir);
}
}
}
// not implemented yet
static function startRecording($users_id) {
if (!User::isAdmin() && User::getId() != $users_id) {
return false;
}
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj)) {
$server = str_replace("stats", "", $obj->stats);
$lt = new LiveTransmition(0);
$lt->loadByUser($users_id);
$key = $lt->getKey();
$appName = self::getApplicationName();
$url = "{$server}control/record/start?app={$appName}&name=$key";
url_get_contents($url);
}
}
static function getApplicationName() {
$obj = AVideoPlugin::getObjectData('Live');
$parts = explode("/", $obj->playerServer);
$live = end($parts);
if (empty($live)) {
$live = "live";
}
return $live;
}
// not implemented yet
static function stopRecording($users_id) {
if (!User::isAdmin() && User::getId() != $users_id) {
return false;
}
$obj = AVideoPlugin::getObjectData("Live");
if (!empty($obj)) {
$server = str_replace("stats", "", $obj->stats);
$lt = new LiveTransmition(0);
$lt->loadByUser($users_id);
$key = $lt->getKey();
$appName = self::getApplicationName();
$url = "{$server}control/record/stop?app={$appName}&name=$key";
url_get_contents($url);
}
}
static function getLinkToLiveFromUsers_id($users_id) {
$live_servers_id = self::getCurrentLiveServersId();
return self::getLinkToLiveFromUsers_idAndLiveServer($users_id, $live_servers_id);
}
static function getLinkToLiveFromUsers_idAndLiveServer($users_id, $live_servers_id) {
if (empty($users_id)) {
return false;
}
global $global;
$user = new User($users_id);
if (empty($user->getChannelName())) {
return false;
}
return self::getLinkToLiveFromChannelNameAndLiveServer($user->getChannelName(), $live_servers_id);
}
static function getLinkToLiveFromChannelNameAndLiveServer($channelName, $live_servers_id) {
global $global;
$live_servers_id = intval($live_servers_id);
$channelName = trim($channelName);
if (empty($channelName)) {
return false;
}
$playlists_id_live = "";
if (!empty($_REQUEST['playlists_id_live'])) {
$playlists_id_live = "?playlists_id_live=" . $_REQUEST['playlists_id_live'];
}
//return "{$global['webSiteRootURL']}plugin/Live/?live_servers_id={$live_servers_id}&c=" . urlencode($channelName);
return "{$global['webSiteRootURL']}live/{$live_servers_id}/" . urlencode($channelName) . $playlists_id_live;
}
static function getAvailableLiveServersId() {
$ls = self::getAvailableLiveServer();
if (empty($ls)) {
return 0;
} else {
return intval($ls->live_servers_id);
}
}
static function getLastServersIdFromUser($users_id) {
$last = LiveTransmitionHistory::getLatestFromUser($users_id);
if (empty($last)) {
return 0;
} else {
return intval($last['live_servers_id']);
}
}
static function getLinkToLiveFromUsers_idWithLastServersId($users_id) {
$live_servers_id = self::getLastServersIdFromUser($users_id);
return self::getLinkToLiveFromUsers_idAndLiveServer($users_id, $live_servers_id);
}
static function getCurrentLiveServersId() {
$live_servers_id = self::getLiveServersIdRequest();
if ($live_servers_id) {
return $live_servers_id;
} else {
return self::getAvailableLiveServersId();
}
}
public function getVideosManagerListButtonTitle() {
global $global;
if (!User::isAdmin()) {
return "";
}
$btn = '
' . __("Live Info") . ' ';
return $btn;
}
public function getPluginMenu() {
global $global;
return ' ' . __('Edit Live Servers') . ' ';
}
static function getStats($force_recreate=false) {
global $getStatsLive, $_getStats, $getStatsObject;
if(!empty($force_recreate)){
unset($getStatsLive);
$_getStats = array();
$getStatsObject = array();
}
if (isset($getStatsLive)) {
return $getStatsLive;
}
$obj = AVideoPlugin::getObjectData("Live");
if (empty($obj->useLiveServers)) {
$getStatsLive = self::_getStats(0);
return $getStatsLive;
} else if (!empty(Live::getLiveServersIdRequest())) {
$ls = new Live_servers(Live::getLiveServersIdRequest());
if (!empty($ls->getPlayerServer())) {
$server = self::_getStats($ls->getId());
$server->live_servers_id = $ls->getId();
$server->playerServer = $ls->getPlayerServer();
$getStatsLive = $server;
return $server;
}
}
$ls = Live_servers::getAllActive();
$liveServers = array();
$getLiveServersIdRequest = self::getLiveServersIdRequest();
foreach ($ls as $value) {
$server = Live_servers::getStatsFromId($value['id']);
if (!empty($server) && is_object($server)) {
$server->live_servers_id = $value['id'];
$server->playerServer = $value['playerServer'];
foreach ($server->applications as $key => $app) {
if(self::isAdaptive($app['key'])){
continue;
}
$_REQUEST['live_servers_id'] = $value['id'];
if (empty($app['key'])) {
$app['key'] = "";
}
$server->applications[$key]['m3u8'] = self::getM3U8File($app['key']);
$server->applications[$key]['isURL200'] = isURL200($server->applications[$key]['m3u8']);
}
$liveServers[] = $server;
} else {
_error_log("Live::getStats Live Server NOT found {$value['id']} " . json_encode($server) . " " . json_encode($value));
}
}
$_REQUEST['live_servers_id'] = $getLiveServersIdRequest;
$getStatsLive = $liveServers;
return $liveServers;
}
static function isAdaptive($key){
$parts = explode("_", $key);
if(!empty($parts[1])){
$adaptive = array('hi', 'low', 'mid');
if(in_array($parts[1], $adaptive)){
return true;
}
}
return false;
}
static function getAllServers() {
$obj = AVideoPlugin::getObjectData("Live");
if (empty($obj->useLiveServers)) {
return array("id" => 0, "name" => __("Default"), "status" => "a", "rtmp_server" => $obj->server, 'playerServer' => $obj->playerServer, "stats_url" => $obj->stats, "disableDVR" => $obj->disableDVR, "disableGifThumbs" => $obj->disableGifThumbs, "useAadaptiveMode" => $obj->useAadaptiveMode, "protectLive" => $obj->protectLive, "getRemoteFile" => "");
} else {
return Live_servers::getAllActive();
}
}
static function getAvailableLiveServer() {
// create 1 min cache
$name = "Live::getAvailableLiveServer";
$return = ObjectYPT::getCache($name, 60);
if (empty($return)) {
$obj = AVideoPlugin::getObjectData("Live");
if (empty($obj->useLiveServers)) {
$return = false;
} else {
$liveServers = self::getStats();
usort($liveServers, function($a, $b) {
if ($a->countLiveStream == $b->countLiveStream) {
return 0;
}
return ($a->countLiveStream < $b->countLiveStream) ? -1 : 1;
});
if (empty($liveServers[0])) {
_error_log("Live::getAvailableLiveServer we could not get server status, try to uncheck useLiveServers parameter from the Live plugin");
return array();
}
$return = $liveServers[0];
ObjectYPT::setCache($name, $return);
}
}
return $return;
}
static function canSeeLiveFromLiveKey($key) {
$lt = self::getLiveTransmitionObjectFromKey($key);
if (empty($lt)) {
return false;
}
return $lt->userCanSeeTransmition();
}
static function isAPrivateLiveFromLiveKey($key) {
$lt = self::getLiveTransmitionObjectFromKey($key);
if (empty($lt)) {
return false;
}
return $lt->isAPrivateLive();
}
+ static function getTitleFromUsers_Id($users_id){
+ $lt = self::getLiveTransmitionObjectFromUsers_id($users_id);
+ return $lt->getTitle();
+ }
+
+ static function getLiveTransmitionObjectFromUsers_id($users_id) {
+ $key = self::getLiveKey($users_id);
+ return self::getLiveTransmitionObjectFromKey($key);
+ }
+
static function getLiveTransmitionObjectFromKey($key) {
global $getLiveTransmitionObjectFromKey;
if (empty($getLiveTransmitionObjectFromKey)) {
$getLiveTransmitionObjectFromKey = array();
}
$parts = explode("_", $key);
if (empty($parts[0])) {
return false;
}
if (!isset($getLiveTransmitionObjectFromKey[$parts[0]])) {
$livet = LiveTransmition::keyExists($parts[0]);
if (empty($livet)) {
$getLiveTransmitionObjectFromKey[$parts[0]] = false;
} else {
$lt = new LiveTransmition($livet['id']);
$getLiveTransmitionObjectFromKey[$parts[0]] = $lt;
}
}
return $getLiveTransmitionObjectFromKey[$parts[0]];
}
static function _getStats($live_servers_id = 0) {
global $global, $_getStats;
if (empty($_REQUEST['name'])) {
//_error_log("Live::_getStats {$live_servers_id} GET " . json_encode($_GET));
//_error_log("Live::_getStats {$live_servers_id} POST " . json_encode($_POST));
//_error_log("Live::_getStats {$live_servers_id} REQUEST " . json_encode($_REQUEST));
$_REQUEST['name'] = "undefined";
}
if (!empty($_getStats[$live_servers_id][$_REQUEST['name']]) && is_object($_getStats[$live_servers_id][$_REQUEST['name']])) {
//_error_log("Live::_getStats cached result {$_REQUEST['name']} " . json_encode($_getStats[$live_servers_id][$_REQUEST['name']]));
return $_getStats[$live_servers_id][$_REQUEST['name']];
}
session_write_close();
$obj = new stdClass();
$obj->error = true;
$obj->msg = "OFFLINE";
$obj->nclients = 0;
$obj->applications = array();
$obj->hidden_applications = array();
$obj->name = $_REQUEST['name'];
$liveUsersEnabled = AVideoPlugin::isEnabledByName("LiveUsers");
$p = AVideoPlugin::loadPlugin("Live");
$xml = $p->getStatsObject($live_servers_id);
$xml = json_encode($xml);
$xml = json_decode($xml);
$stream = false;
$lifeStream = array();
//$obj->server = $xml->server;
if (!empty($xml->server->application) && !is_array($xml->server->application)) {
$application = $xml->server->application;
$xml->server->application = array();
$xml->server->application[] = $application;
}
foreach ($xml->server->application as $key => $application) {
if (!empty($application->live->stream)) {
if (empty($lifeStream)) {
$lifeStream = array();
}
$stream = $application->live->stream;
if (empty($application->live->stream->name) && !empty($application->live->stream[0]->name)) {
foreach ($application->live->stream as $stream) {
if(Live::isAdaptive($stream->name)){
continue;
}
$lifeStream[] = $stream;
}
} else {
if(Live::isAdaptive($stream->name)){
continue;
}
$lifeStream[] = $application->live->stream;
}
}
}
$obj->disableGif = $p->getDisableGifThumbs();
$obj->countLiveStream = count($lifeStream);
foreach ($lifeStream as $value) {
if (!empty($value->name)) {
$row = LiveTransmition::keyExists($value->name);
if (empty($row['users_id'])) {
continue;
}
if (!empty($row) && $value->name === $obj->name) {
$obj->msg = "ONLINE";
}
$title = $row['title'];
$u = new User($row['users_id']);
$hiddenName = preg_replace('/^(.{5})/', '*****', $value->name);
if (!self::canSeeLiveFromLiveKey($value->name)) {
$obj->hidden_applications[] = "{$row['channelName']} ($hiddenName} is a private live";
if (!User::isAdmin()) {
continue;
} else {
$title .= " (private live)";
}
} else
if (empty($row) || empty($row['public'])) {
$obj->hidden_applications[] = "{$row['channelName']} ($hiddenName} is set to not be listed";
if (!User::isAdmin()) {
continue;
} else {
$title .= " (set to not be listed)";
}
} else
if ($u->getStatus() !== 'a') {
$obj->hidden_applications[] = "{$row['channelName']} {$hiddenName} the user is inactive";
if (!User::isAdmin()) {
continue;
} else {
$title .= " (user is inactive)";
}
}
$users = false;
if ($liveUsersEnabled) {
$filename = $global['systemRootPath'] . 'plugin/LiveUsers/Objects/LiveOnlineUsers.php';
if (file_exists($filename)) {
require_once $filename;
$liveUsers = new LiveOnlineUsers(0);
$users = $liveUsers->getUsersFromTransmitionKey($value->name, $live_servers_id);
}
}
$userName = $u->getNameIdentificationBd();
$user = $u->getUser();
$channelName = $u->getChannelName();
$photo = $u->getPhotoDB();
$poster = $global['webSiteRootURL'] . $p->getPosterImage($row['users_id'], $live_servers_id);
$playlists_id_live = 0;
if (preg_match("/.*_([0-9]+)/", $value->name, $matches)) {
if (!empty($matches[1])) {
$_REQUEST['playlists_id_live'] = intval($matches[1]);
$playlists_id_live = $_REQUEST['playlists_id_live'];
$photo = PlayLists::getImage($_REQUEST['playlists_id_live']);
$title = PlayLists::getNameOrSerieTitle($_REQUEST['playlists_id_live']);
}
}
$link = Live::getLinkToLiveFromChannelNameAndLiveServer($u->getChannelName(), $live_servers_id);
// this variable is to keep it compatible for Mobile app
$UserPhoto = $photo;
$key = LiveTransmition::keyNameFix($value->name);
$m3u8 = self::getM3U8File($key);
$obj->applications[] = array(
"key" => $key,
"isPrivate" => self::isAPrivateLiveFromLiveKey($value->name),
"users" => $users,
"name" => $userName,
"user" => $user,
"photo" => $photo,
"UserPhoto" => $UserPhoto,
"title" => $title,
'channelName' => $channelName,
'poster' => $poster,
'link' => addQueryStringParameter($link, 'embed', 1),
'href' => $link,
'playlists_id_live' => $playlists_id_live,
'm3u8' => $m3u8,
'isURL200' => isURL200($m3u8)
);
if ($value->name === $obj->name) {
$obj->error = property_exists($value, 'publishing') ? false : true;
$obj->msg = (!$obj->error) ? "ONLINE" : "Waiting for Streamer";
$obj->stream = $value;
$obj->nclients = intval($value->nclients);
break;
}
}
}
$obj->error = false;
$_getStats[$live_servers_id][$_REQUEST['name']] = $obj;
//_error_log("Live::_getStats NON cached result {$_REQUEST['name']} " . json_encode($obj));
return $obj;
}
static function getImage($users_id, $live_servers_id, $playlists_id_live = 0) {
$p = AVideoPlugin::loadPlugin("Live");
if (self::isLive($users_id)) {
$url = $p->getLivePosterImage($users_id, $live_servers_id);
$url = addQueryStringParameter($url, "playlists_id_live", $playlists_id_live);
} else {
$file = self::getOfflineImage(false);
}
return $url;
}
static function isLive($users_id, $live_servers_id = 0, $force_recreate=false) {
if(empty($users_id)){
return false;
}
$key = self::getLiveKey($users_id);
return self::isLiveAndIsReadyFromKey($key, $live_servers_id, $force_recreate=false);
}
static function isLiveFromKey($key, $live_servers_id = 0, $force_recreate=false) {
if(empty($key)){
return false;
}
$json = self::getStats($force_recreate);
if (!empty($json) && is_object($json) && !empty($json->applications)) {
foreach ($json->applications as $value) {
if (preg_match("/{$key}.*/", $value['key'])) {
if (empty($live_servers_id)) {
return true;
} else {
if ($value['live_servers_id'] == $live_servers_id) {
return true;
}
}
}
}
}
return false;
}
static function isLiveAndIsReadyFromKey($key, $live_servers_id = 0, $force_recreate=false) {
$m3u8 = self::getM3U8File($key);
$isLiveFromKey = self::isLiveFromKey($key, $live_servers_id, $force_recreate);
$is200 = isURL200($m3u8);
_error_log("isLiveFromKey: {$isLiveFromKey}");
_error_log("m3u8: {$m3u8}");
_error_log("is200: {$is200}");
return $isLiveFromKey && $is200;
}
static function getOnlineLivesFromUser($users_id) {
$key = self::getLiveKey($users_id);
$json = self::getStats();
$lives = array();
if (!empty($json) && is_object($json) && !empty($json->applications)) {
foreach ($json->applications as $value) {
if (preg_match("/{$key}.*/", $value['key'])) {
$lives[] = $value;
}
}
}
return $lives;
}
static function keyIsFromPlaylist($key) {
$parts = explode("_", $key);
if (empty($parts[1])) {
return false;
}
return array('key' => $parts[0], 'playlists_id' => $parts[1]);
}
static function getLiveKey($users_id) {
$lt = new LiveTransmition(0);
$lt->loadByUser($users_id);
return $lt->getKey();
}
public function getImageGif($users_id, $live_servers_id = 0, $playlists_id_live = 0) {
global $global;
if (empty($live_servers_id)) {
$live_servers_id = self::getCurrentLiveServersId();
}
$u = new User($users_id);
$username = $u->getUser();
$file = "plugin/Live/getImage.php?live_servers_id={$live_servers_id}&u={$username}&format=gif";
$url = $global['webSiteRootURL'] . $file;
$url = addQueryStringParameter($url, "playlists_id_live", $playlists_id_live);
return $url;
}
public static function getPosterImage($users_id, $live_servers_id) {
global $global;
$file = self::_getPosterImage($users_id, $live_servers_id);
if (!file_exists($global['systemRootPath'] . $file)) {
$file = "plugin/Live/view/OnAir.jpg";
}
return $file;
}
public function getLivePosterImage($users_id, $live_servers_id = 0) {
global $global;
return $global['webSiteRootURL'] . self::getLivePosterImageRelativePath($users_id, $live_servers_id);
}
public function getLivePosterImageRelativePath($users_id, $live_servers_id = 0) {
global $global;
if (empty($live_servers_id)) {
$live_servers_id = self::getCurrentLiveServersId();
}
if (self::isLiveThumbsDisabled()) {
$file = self::_getPosterImage($users_id, $live_servers_id);
if (!file_exists($global['systemRootPath'] . $file)) {
$file = "plugin/Live/view/OnAir.jpg";
}
} else {
$u = new User($users_id);
$username = $u->getUser();
$file = "plugin/Live/getImage.php?live_servers_id={$live_servers_id}&u={$username}&format=jpg";
}
return $file;
}
public static function isLiveThumbsDisabled() {
$obj = AVideoPlugin::getDataObject("Live");
if (!empty($obj->disableLiveThumbs)) {
return true;
}
return false;
}
public function getPosterThumbsImage($users_id, $live_servers_id) {
global $global;
$file = self::_getPosterThumbsImage($users_id, $live_servers_id);
if (!file_exists($global['systemRootPath'] . $file)) {
$file = self::getOnAirImage(false);
}
return $file;
}
static function getOfflineImage($includeURL = true) {
global $global;
$img = "plugin/Live/view/Offline.jpg";
if ($includeURL) {
$img = "{$global['webSiteRootURL']}{$img}";
}
return $img;
}
static function getOnAirImage($includeURL = true) {
global $global;
$img = "plugin/Live/view/OnAir.jpg";
if ($includeURL) {
$img = "{$global['webSiteRootURL']}{$img}";
}
return $img;
}
public static function _getPosterImage($users_id, $live_servers_id) {
$file = "videos/userPhoto/Live/user_{$users_id}_bg_{$live_servers_id}.jpg";
return $file;
}
public function _getPosterThumbsImage($users_id, $live_servers_id) {
$file = "videos/userPhoto/Live/user_{$users_id}_thumbs_{$live_servers_id}.jpg";
return $file;
}
public static function on_publish($liveTransmitionHistory_id) {
$obj = AVideoPlugin::getDataObject("Live");
if (empty($obj->disableRestream)) {
self::restream($liveTransmitionHistory_id);
}
}
public static function getRestreamObject($liveTransmitionHistory_id) {
if (empty($liveTransmitionHistory_id)) {
return false;
}
$lth = new LiveTransmitionHistory($liveTransmitionHistory_id);
if (empty($lth->getKey())) {
return false;
}
$_REQUEST['live_servers_id'] = $lth->getLive_servers_id();
$obj = new stdClass();
$obj->m3u8 = self::getM3U8File($lth->getKey(), true);
$obj->restreamerURL = self::getRestreamer($lth->getLive_servers_id());
$obj->restreamsDestinations = array();
$obj->token = getToken(60);
$obj->users_id = $lth->getUsers_id();
$rows = Live_restreams::getAllFromUser($lth->getUsers_id());
foreach ($rows as $value) {
$value['stream_url'] = rtrim($value['stream_url'], "/") . '/';
$obj->restreamsDestinations[] = "{$value['stream_url']}{$value['stream_key']}";
}
return $obj;
}
public static function restream($liveTransmitionHistory_id) {
ignore_user_abort(true);
ob_start();
header("Connection: close");
@header("Content-Length: " . ob_get_length());
ob_end_flush();
flush();
try {
$obj = self::getRestreamObject($liveTransmitionHistory_id);
if (empty($obj)) {
return false;
}
$data_string = json_encode($obj);
_error_log("Live:restream ({$obj->restreamerURL}) {$data_string}");
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $obj->restreamerURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output);
} catch (Exception $exc) {
_error_log("Live:restream " . $exc->getTraceAsString());
}
return false;
}
public static function canStreamWithMeet() {
if (!User::canStream()) {
return false;
}
if (!User::canCreateMeet()) {
return false;
}
$mobj = AVideoPlugin::getObjectDataIfEnabled("Meet");
if (empty($mobj)) {
return false;
}
$obj = AVideoPlugin::getObjectDataIfEnabled("Live");
if (!empty($obj->disableMeetCamera)) {
return false;
}
return true;
}
public function getUploadMenuButton() {
global $global;
$obj = $this->getDataObject();
if (!empty($obj->doNotShowGoLiveButton) || !User::canStream()) {
return '';
}
$buttonTitle = $this->getButtonTitle();
//include $global['systemRootPath'] . 'plugin/Live/getUploadMenuButton.php';
}
public static function getAllVideos($status = "", $showOnlyLoggedUserVideos = false, $activeUsersOnly = true) {
global $global, $config, $advancedCustom;
if (AVideoPlugin::isEnabledByName("VideoTags")) {
if (!empty($_GET['tags_id']) && empty($videosArrayId)) {
TimeLogStart("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})");
$videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']);
TimeLogEnd("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})", __LINE__);
}
}
$status = str_replace("'", "", $status);
$sql = "SELECT u.*, v.*, c.iconClass, c.name as category, c.clean_name as clean_category,c.description as category_description, v.created as videoCreation, v.modified as videoModified "
. " FROM live_transmitions as v "
. " LEFT JOIN categories c ON categories_id = c.id "
. " LEFT JOIN users u ON v.users_id = u.id "
. " WHERE 1=1 ";
if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) {
$uid = intval(User::getId());
$sql .= " AND v.users_id = '{$uid}'";
} elseif (!empty($showOnlyLoggedUserVideos)) {
$uid = intval($showOnlyLoggedUserVideos);
$sql .= " AND v.users_id = '{$uid}'";
} elseif (!empty($_GET['channelName'])) {
$user = User::getChannelOwner($_GET['channelName']);
$uid = intval($user['id']);
$sql .= " AND v.users_id = '{$uid}' ";
}
if ($activeUsersOnly) {
$sql .= " AND u.status = 'a' ";
}
if ($status == "publicOnly") {
$sql .= " AND v.public = 1 ";
} elseif (!empty($status)) {
$sql .= " AND v.`public` = '{$status}'";
}
if (!empty($_GET['catName'])) {
$catName = $global['mysqli']->real_escape_string($_GET['catName']);
$sql .= " AND (c.clean_name = '{$catName}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$catName}' ))";
}
if (!empty($_GET['modified'])) {
$_GET['modified'] = str_replace("'", "", $_GET['modified']);
$sql .= " AND v.modified >= '{$_GET['modified']}'";
}
$sql .= AVideoPlugin::getVideoWhereClause();
if (strpos(strtolower($sql), 'limit') === false) {
if (!empty($_GET['limitOnceToOne'])) {
$sql .= " LIMIT 1";
unset($_GET['limitOnceToOne']);
}else{
$_REQUEST['rowCount'] = getRowCount();
if (!empty($_REQUEST['rowCount'])) {
$sql .= " LIMIT {$_REQUEST['rowCount']}";
} else {
_error_log("getAllVideos without limit " . json_encode(debug_backtrace()));
if (empty($global['limitForUnlimitedVideos'])) {
$global['limitForUnlimitedVideos'] = 100;
}
if ($global['limitForUnlimitedVideos'] > 0) {
$sql .= " LIMIT {$global['limitForUnlimitedVideos']}";
}
}
}
}
//echo $sql;exit;
//_error_log("getAllVideos($status, $showOnlyLoggedUserVideos , $ignoreGroup , ". json_encode($videosArrayId).")" . $sql);
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$videos = array();
if ($res != false) {
foreach ($fullData as $row) {
unset($row['password']);
unset($row['recoverPass']);
$row['live_servers_id'] = self::getLastServersIdFromUser($row['users_id']);
if (empty($otherInfo)) {
$otherInfo = array();
$otherInfo['category'] = xss_esc_back($row['category']);
$otherInfo['groups'] = UserGroups::getVideoGroups($row['id']);
//$otherInfo['title'] = UTF8encode($row['title']);
$otherInfo['description'] = UTF8encode($row['description']);
$otherInfo['descriptionHTML'] = Video::htmlDescription($otherInfo['description']);
$otherInfo['filesize'] = 0;
}
foreach ($otherInfo as $key => $value) {
$row[$key] = $value;
}
$row['rotation'] = 0;
$row['filename'] = '';
$row['type'] = 'live';
$row['duration'] = '';
$row['isWatchLater'] = 0;
$row['isFavorite'] = 0;
$row['views_count'] = 0;
$videos[] = $row;
}
//$videos = $res->fetch_all(MYSQLI_ASSOC);
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $videos;
}
}
diff --git a/plugin/YPTWallet/YPTWallet.php b/plugin/YPTWallet/YPTWallet.php
index 6809e8869..d90e2f8f2 100644
--- a/plugin/YPTWallet/YPTWallet.php
+++ b/plugin/YPTWallet/YPTWallet.php
@@ -1,647 +1,635 @@
decimalPrecision = 2;
$obj->wallet_button_title = "My Wallet";
$obj->add_funds_text = "Adding money instantly from credit/debit card Add funds on your Account Balance, to support our videos";
$obj->add_funds_success_success = "Thank you, Your funds has been added";
$obj->add_funds_success_cancel = "Ops, You have cancel it";
$obj->add_funds_success_fail = "Sorry, Your funds request has been fail";
$obj->transfer_funds_text = "Transfer money for other users Transfer funds from your account to another user account";
$obj->transfer_funds_success_success = "Thank you, Your funds has been transfered";
$obj->transfer_funds_success_fail = "Sorry, Your funds transfer request has been fail";
$obj->withdraw_funds_text = "Withdraw money from your Transfer funds from your account to your credit card or bank account";
$obj->withdraw_funds_success_success = "Thank you, Your request was submited";
$obj->withdraw_funds_success_fail = "Sorry, Your funds withdraw request has been fail";
$obj->virtual_currency = "HEART"; // we will show this currency on the wallet but we will not make transactions on the payment gateway with it
$obj->virtual_currency_symbol = "❤"; // we will show this currency on the wallet but we will not make transactions on the payment gateway with it
$obj->virtual_currency_exchange_rate = "2"; // means 1 real currency will be 2 virtual currencies
$obj->virtual_currency_decimalPrecision = 2.5; // the value 2.5 on it means if you purchase 2 real currency it will worth 5 virtual currencies
$obj->virtual_currency_enable = false;
$obj->currency = "USD";
$obj->currency_symbol = "$";
$obj->addFundsOptions = "[5,10,20,50]";
$obj->showWalletOnlyToAdmin = false;
$obj->CryptoWalletName = "Bitcoin Wallet Address";
$obj->enableAutomaticAddFundsPage = true;
// add funds
$obj->enableManualAddFundsPage = false;
$obj->manualAddFundsMenuTitle = "Add Funds/Deposit";
$obj->manualAddFundsPageButton = "Notify Deposit Made";
$obj->manualAddFundsNotifyEmail = "yourEmail@yourDomain.com";
$obj->manualAddFundsTransferFromUserId = 1;
// sell funds
$obj->enableManualWithdrawFundsPage = true;
$obj->withdrawFundsOptions = "[5,10,20,50,100,1000]";
$obj->manualWithdrawFundsMenuTitle = "Withdraw Funds";
$obj->manualWithdrawFundsPageButton = "Request Withdraw";
$obj->manualWithdrawFundsNotifyEmail = "yourEmail@yourDomain.com";
$obj->manualWithdrawFundsminimum = 1;
$obj->manualWithdrawFundsmaximum = 100;
$obj->manualWithdrawFundsTransferToUserId = 1;
$plugins = self::getAvailablePlugins();
foreach ($plugins as $value) {
$eval = "\$obj->enablePlugin_{$value} = false;";
eval($eval);
$dataObj = self::getPluginDataObject($value);
$obj = (object) array_merge((array) $obj, (array) $dataObj);
}
return $obj;
}
public function getBalance($users_id)
{
$wallet = self::getWallet($users_id);
return $wallet->getBalance();
}
public function getBalanceText($users_id)
{
$balance = $this->getBalanceFormated($users_id);
return self::formatCurrency($balance);
}
public function getBalanceFormated($users_id)
{
$balance = $this->getBalance($users_id);
$obj = $this->getDataObject();
return number_format($balance, $obj->decimalPrecision);
}
public static function formatCurrency($value, $addHTML=false, $doNotUseVirtualCurrency = false)
{
$value = floatval($value);
$obj = AVideoPlugin::getObjectData('YPTWallet');
$currency_symbol = $obj->currency_symbol;
$decimalPrecision = $obj->decimalPrecision;
$currency = $obj->currency;
if (empty($doNotUseVirtualCurrency) && $obj->virtual_currency_enable) {
$currency_symbol = $obj->virtual_currency_symbol;
$decimalPrecision = $obj->virtual_currency_decimalPrecision;
$currency = $obj->virtual_currency;
}
$value = number_format($value, $decimalPrecision);
if ($addHTML) {
return "{$currency_symbol} {$value} {$currency}";
} else {
return "{$currency_symbol} {$value} {$currency}";
}
}
public static function getStep($doNotUseVirtualCurrency = false)
{
$obj = AVideoPlugin::getObjectData('YPTWallet');
$decimalPrecision = $obj->decimalPrecision;
if ($obj->virtual_currency_enable) {
$decimalPrecision = $obj->virtual_currency_decimalPrecision;
}
if (empty($decimalPrecision)) {
return 1;
}
return "0.".str_repeat("0", $decimalPrecision-1)."1";
}
public static function formatFloat($value)
{
$value = floatval($value);
$obj = AVideoPlugin::getObjectData('YPTWallet');
return number_format($value, $obj->decimalPrecision);
}
public static function getWallet($users_id)
{
$wallet = new Wallet(0);
$wallet->setUsers_id($users_id);
return $wallet;
}
public function getOrCreateWallet($users_id)
{
$wallet = new Wallet(0);
$wallet->setUsers_id($users_id);
if (empty($wallet->getId())) {
$wallet_id = $wallet->save();
$wallet = new Wallet($wallet_id);
}
return $wallet;
}
public function getAllUsers($activeOnly = true)
{
global $global;
$sql = "SELECT w.*, u.*, u.id as user_id, IFNULL(balance, 0) as balance FROM users u "
. " LEFT JOIN wallet w ON u.id = w.users_id WHERE 1=1 ";
if ($activeOnly) {
$sql .= " AND status = 'a' ";
}
$sql .= BootGrid::getSqlFromPost(array('name', 'email', 'user'));
$res = $global['mysqli']->query($sql);
$user = array();
if ($res) {
while ($row = $res->fetch_assoc()) {
$row['name'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $row['name']);
$row['identification'] = User::getNameIdentificationById($row['user_id']);
$row['identification'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $row['identification']);
unset($row['about']);
$row['background'] = User::getBackground($row['user_id']);
$row['photo'] = User::getPhoto($row['user_id']);
$row['crypto_wallet_address'] = "";
$user[] = $row;
}
//$user = $res->fetch_all(MYSQLI_ASSOC);
} else {
$user = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $user;
}
public static function getTotalBalance()
{
global $global;
$sql = "SELECT sum(balance) as total FROM wallet ";
$res = $global['mysqli']->query($sql);
$user = array();
if ($res) {
if ($row = $res->fetch_assoc()) {
return $row['total'];
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return 0;
}
public static function getTotalBalanceText()
{
$value = self::getTotalBalance();
return self::formatCurrency($value);
}
public function getHistory($user_id)
{
$wallet = self::getWallet($user_id);
$log = new WalletLog(0);
$rows = $log->getAllFromWallet($wallet->getId());
return $rows;
}
public static function exchange($value)
{
$obj = AVideoPlugin::getObjectData('YPTWallet');
$value = floatval($value);
$virtual_currency_exchange_rate = floatval($obj->virtual_currency_exchange_rate);
if (!empty($virtual_currency_exchange_rate)) {
$value *= $virtual_currency_exchange_rate;
}
return $value;
}
/**
*
* @param type $users_id
* @param type $value
* @param type $description
* @param type $json_data
* @param type $mainWallet_user_id A user ID where the money comes from and where the money goes for
*/
public function addBalance($users_id, $value, $description = "", $json_data = "{}", $mainWallet_user_id = 0, $noNotExchangeValue = false)
{
global $global;
$obj = $this->getDataObject();
if (empty($noNotExchangeValue) && !empty($obj->virtual_currency_enable)) {
$originalValue = $value;
$value = self::exchange($value);
$originalValueFormated = self::formatCurrency($originalValue, false, true);
$valueFormated = self::formatCurrency($value);
$description .= " Rate Exchanged {$originalValueFormated} => {$valueFormated} ";
}
$wallet = $this->getOrCreateWallet($users_id);
$balance = $wallet->getBalance();
_error_log("YPTWallet::addBalance BEFORE (user_id={$users_id}) (balance={$balance})");
$balance += $value;
$wallet->setBalance($balance);
$wallet_id = $wallet->save();
WalletLog::addLog($wallet_id, $value, $description, $json_data, "success", "addBalance");
if (!empty($mainWallet_user_id)) {
$wallet = $this->getOrCreateWallet($mainWallet_user_id);
$balance = $wallet->getBalance();
$balance += ($value * -1);
$wallet->setBalance($balance);
$wallet_id = $wallet->save();
$user = new User($users_id);
WalletLog::addLog($wallet_id, ($value * -1), " From user ($users_id) " . $user->getUser() . " - " . $description, $json_data, "success", "addBalance to main wallet");
}
$wallet = $this->getOrCreateWallet($users_id);
$balance = $wallet->getBalance();
_error_log("YPTWallet::addBalance AFTER (user_id={$users_id}) (balance={$balance})");
//_error_log("YPTWallet::addBalance $wallet_id, $value, $description, $json_data");
}
public function saveBalance($users_id, $value)
{
if (!User::isAdmin()) {
return false;
}
$wallet = self::getWallet($users_id);
$balance = $wallet->getBalance();
$wallet->setBalance($value);
$wallet_id = $wallet->save();
$description = "Admin set your balance, from {$balance} to {$value}";
WalletLog::addLog($wallet_id, $value, $description, "{}", "success", "saveBalance");
}
public static function transferBalanceToSiteOwner($users_id_from, $value, $description = "", $forceTransfer = false)
{
$obj = AVideoPlugin::getObjectData('YPTWallet');
if (empty($obj->manualWithdrawFundsTransferToUserId)) {
_error_log("YPTWallet::transferBalanceToSiteOwner site owner is not defined in the plugin, define it on the option manualWithdrawFundsTransferToUserId", AVideoLog::$ERROR);
}
return self::transferBalance($users_id_from, $obj->manualWithdrawFundsTransferToUserId, $value, $description, $forceTransfer);
}
public static function transferBalanceFromSiteOwner($users_id_from, $value, $description = "", $forceTransfer = false)
{
$obj = AVideoPlugin::getObjectData('YPTWallet');
return self::transferBalance($obj->manualWithdrawFundsTransferToUserId, $users_id_from, $value, $description, $forceTransfer);
}
public static function transferBalanceFromMeToSiteOwner($value)
{
if (!User::isLogged()) {
return false;
}
return self::transferBalanceToSiteOwner(User::getId(), $value);
}
public static function transferBalanceFromOwnerToMe($value)
{
if (!User::isLogged()) {
return false;
}
return self::transferBalanceFromSiteOwner(User::getId(), $value);
}
public static function transferBalance($users_id_from, $users_id_to, $value, $forceDescription = "", $forceTransfer = false)
{
global $global;
_error_log("transferBalance: $users_id_from, $users_id_to, $value, $forceDescription, $forceTransfer");
if (!User::isAdmin()) {
if ($users_id_from != User::getId() && !$forceTransfer) {
_error_log("transferBalance: you are not admin, $users_id_from,$users_id_to, $value");
return false;
}
}
if (!User::idExists($users_id_from) || !User::idExists($users_id_to)) {
_error_log("transferBalance: user does not exists, $users_id_from,$users_id_to, $value");
return false;
}
$value = floatval($value);
if ($value <= 0) {
return false;
}
$wallet = self::getWallet($users_id_from);
$balance = $wallet->getBalance();
$newBalance = $balance - $value;
if ($newBalance < 0) {
_error_log("transferBalance: you dont have balance, $users_id_from,$users_id_to, $value (Balance: {$balance}) (New Balance: {$newBalance})");
return false;
}
$identificationFrom = User::getNameIdentificationById($users_id_from);
$identificationTo = User::getNameIdentificationById($users_id_to);
$wallet->setBalance($newBalance);
$wallet_id = $wallet->save();
$description = "Transfer Balance {$value} from YOU to user {$identificationTo} ";
if (!empty($forceDescription)) {
$description = $forceDescription;
}
WalletLog::addLog($wallet_id, "-" . $value, $description, "{}", "success", "transferBalance to");
$wallet = self::getWallet($users_id_to);
$balance = $wallet->getBalance();
$newBalance = $balance + $value;
$wallet->setBalance($newBalance);
$wallet_id = $wallet->save();
$description = "Transfer Balance {$value} from user {$identificationFrom} to YOU ";
if (!empty($forceDescription)) {
$description = $forceDescription;
}
ObjectYPT::clearSessionCache();
WalletLog::addLog($wallet_id, $value, $description, "{}", "success", "transferBalance from");
return true;
}
public function getHTMLMenuRight()
{
global $global;
if (!User::isLogged()) {
return "";
}
$obj = $this->getDataObject();
if ($obj->showWalletOnlyToAdmin && !User::isAdmin()) {
return "";
}
include $global['systemRootPath'] . 'plugin/YPTWallet/view/menuRight.php';
}
public static function getAvailablePayments()
{
global $global;
if (!User::isLogged()) {
- $redirectUri = getSelfURI();
- if (!empty($redirectUri)) {
- $redirectUri = "&redirectUri=" . urlencode($redirectUri);
- }
- echo '';
+ echo getButtonSignInAndUp();
return false;
}
$dir = self::getPluginDir();
$plugins = self::getEnabledPlugins();
foreach ($plugins as $value) {
$subdir = $dir . DIRECTORY_SEPARATOR . $value . DIRECTORY_SEPARATOR;
$file = $subdir . "{$value}.php";
if (is_dir($subdir) && file_exists($file)) {
require_once $file;
$eval = "\$obj = new {$value}();\$obj->getAprovalButton();";
eval($eval);
}
}
return true;
}
public static function getAvailableRecurrentPayments()
{
global $global;
if (!User::isLogged()) {
$redirectUri = getSelfURI();
if (!empty($redirectUri)) {
$redirectUri = "&redirectUri=" . urlencode($redirectUri);
}
- echo '';
+ echo getButtonSignUp(). getButtonSignIn();;
return false;
}
$dir = self::getPluginDir();
$plugins = self::getEnabledPlugins();
foreach ($plugins as $value) {
$subdir = $dir . DIRECTORY_SEPARATOR . $value . DIRECTORY_SEPARATOR;
$file = $subdir . "{$value}.php";
if (is_dir($subdir) && file_exists($file)) {
require_once $file;
$eval = "\$obj = new {$value}();\$obj->getRecurrentAprovalButton();";
eval($eval);
}
}
}
public static function getAvailablePlugins()
{
$dir = self::getPluginDir();
$dirs = scandir($dir);
$plugins = array();
foreach ($dirs as $key => $value) {
if (!in_array($value, array(".", ".."))) {
$subdir = $dir . DIRECTORY_SEPARATOR . $value . DIRECTORY_SEPARATOR;
$file = $subdir . "{$value}.php";
if (is_dir($subdir) && file_exists($file)) {
$plugins[] = $value;
}
}
}
return $plugins;
}
public static function getEnabledPlugins()
{
global $global;
$plugins = self::getAvailablePlugins();
$wallet = new YPTWallet();
$obj = $wallet->getDataObject();
foreach ($plugins as $key => $value) {
$eval = "\$val = \$obj->enablePlugin_{$value};";
eval($eval);
if (empty($val)) {
unset($plugins[$key]);
}
}
return $plugins;
}
public static function getPluginDataObject($pluginName)
{
$dir = self::getPluginDir();
$file = $dir . "/{$pluginName}/{$pluginName}.php";
if (file_exists($file)) {
require_once $file;
$eval = "\$obj = new {$pluginName}();";
eval($eval);
return $obj->getEmptyDataObject();
}
return array();
}
public static function getPluginDir()
{
global $global;
$dir = $global['systemRootPath'] . "plugin/YPTWallet/plugins";
return $dir;
}
public function sendEmails($emailsArray, $subject, $message)
{
global $global, $config;
$siteTitle = $config->getWebSiteTitle();
$footer = $config->getWebSiteTitle();
$body = $this->replaceTemplateText($siteTitle, $footer, $message);
return $this->send($emailsArray, $subject, $body);
}
private function replaceTemplateText($siteTitle, $footer, $message)
{
global $global, $config;
$text = file_get_contents("{$global['systemRootPath']}plugin/YPTWallet/template.html");
$words = array($siteTitle, $footer, $message);
$replace = array('{siteTitle}', '{footer}', '{message}');
return str_replace($replace, $words, $text);
}
private function send($emailsArray, $subject, $body)
{
if (empty($emailsArray)) {
return false;
}
$emailsArray = array_unique($emailsArray);
global $global, $config;
//Create a new PHPMailer instance
$mail = new \PHPMailer\PHPMailer\PHPMailer;
setSiteSendMessage($mail);
//Set who the message is to be sent from
$mail->setFrom($config->getContactEmail(), $config->getWebSiteTitle());
//Set who the message is to be sent to
foreach ($emailsArray as $value) {
if (empty($value)) {
continue;
}
$mail->addBCC($value);
}
//Set the subject line
$mail->Subject = $subject;
$mail->msgHTML($body);
//send the message, check for errors
if (!$mail->send()) {
_error_log("Wallet email FAIL [{$subject}] {$mail->ErrorInfo}");
return false;
} else {
_error_log("Wallet email sent [{$subject}]");
return true;
}
}
/**
*
* @param type $wallet_log_id
* @param type $new_status
* return true if balance is enought
*/
public function processStatus($wallet_log_id, $new_status)
{
$obj = $this->getDataObject();
$walletLog = new WalletLog($wallet_log_id);
$wallet = new Wallet($walletLog->getWallet_id());
$oldStatus = $walletLog->getStatus();
if ($walletLog->getType() == self::MANUAL_WITHDRAW) {
if ($new_status != $oldStatus) {
if ($oldStatus == "success" || $oldStatus == "pending") {
if ($new_status == "canceled") {
// return the value
return self::transferBalance($obj->manualWithdrawFundsTransferToUserId, $wallet->getUsers_id(), $walletLog->getValue());
} else {
// keep the value
return true;
}
}
// get the value again
if ($oldStatus == "canceled") {
return self::transferBalance($wallet->getUsers_id(), $obj->manualWithdrawFundsTransferToUserId, $walletLog->getValue());
}
}
} elseif ($walletLog->getType() == self::MANUAL_ADD) {
if ($oldStatus == "pending") {
if ($new_status == "canceled") {
// do nothing
return true;
} elseif ($new_status == "success") {
// transfer the value
return self::transferBalance($obj->manualAddFundsTransferFromUserId, $wallet->getUsers_id(), $walletLog->getValue());
}
} elseif ($oldStatus == "success") {
//get the money back
return self::transferBalance($wallet->getUsers_id(), $obj->manualAddFundsTransferFromUserId, $walletLog->getValue());
} elseif ($oldStatus == "canceled") {
if ($new_status == "pending") {
// do nothing
return true;
} elseif ($new_status == "success") {
// transfer the value
return self::transferBalance($obj->manualAddFundsTransferFromUserId, $wallet->getUsers_id(), $walletLog->getValue());
}
}
}
return true;
}
public static function getUserBalance($users_id=0)
{
if (empty($users_id)) {
$users_id = User::getId();
}
if (empty($users_id)) {
return 0;
}
$wallet = self::getWallet($users_id);
return $wallet->getBalance();
}
public function getFooterCode()
{
global $global;
$obj = $this->getDataObject();
$js = "";
$js .= "";
return $js;
}
}
diff --git a/view/img/social/parler.png b/view/img/social/parler.png
deleted file mode 100644
index 67ea81745..000000000
Binary files a/view/img/social/parler.png and /dev/null differ